detecting and hiding dynamically creating div after a specific seconds (not onclick) - html

i have a dynamically generating div which is not in the time of loading. It is generating later in the document. So how can i target that div and hide it after specific time. The div is as follows:
<div class="message-sent">Your Message has been sent</div>
Important: I refer so many articles but everyone is talking about 'onclick'. I don't want click event. I just want hide this div when it is appearing in the docuemnt. Thanks in advance!

you can add a style display:none.
you can add the style after time out (3000ms) like so:
setTimeout(function(){
document.getElementsByClassName("message-sent")[0].style.display="none";
}, 3000);
note: it is better if you use an id instead of a class to identify your div.

You should try looking into the setTimeout function.
Also if that div is the only member of the DOM-tree that has that class, use an ID. It's better IMO.
Anyway, assuming you want to hide every member of the message-sent-class,
it goes something like this:
setTimeout(function(){
$('.message-sent').hide();
}, 2000)
In which the 2000is the variable that indicates the time (milliseconds)

You can try DOMNodeInserted,
$(document).bind('DOMNodeInserted', function(event) {
var element = document.getElementsByClassName("message-sent"); // get all elements with class message-sent
var lastchild = element[element.length - 1]; // get the last one (others are hidden)
if(lastchild != null){
lastchild.style.visibility = 'hidden'; // set visibility to hidden
}
});
Working demo
Hope helps,

Related

Having trouble with jquery dynamic input and regex matching. Partially works

I have a dynamic input field where a user can add as many colors as he wants using an "Add" button.
The array works fine. Posts fine. My issue is with a some regex matching. Basically if a user enters one of the colors in the regex pattern a div container with another input shows. This works fine.
The issue:
User enters "purple" - no match, nothing shows. Good.
User enters "blue" - match, div shows. user deletes "blue" div disappears. Good.
User enters "red" - match, div appears. Good.
User enters "yellow" - no match, div disappears. Not Good.
Once the match has occurred I need the div to stay visible. What's happening though is it's removing the div if the next input is not a match.
$("#add").click(function(e){
$('input[name="item_color[]"]').keyup(function() {
var data = $(this).val();
var regx = /(blue|red|orange)/gmi;
if (data.match(regx)){
$("#divcolor").show();
}
else {
$("#divcolor").hide();
}
});
});
I've tried removing the
$("#divcolor").hide();
which somewhat works. except if the user goes back through the inputs and deletes the match that caused the div to show initially the div continues to show.
Basically I just need it to show the div if any match occurs in any of the inputs and hide the div if no matches occur. I really need the div to show/hide on keyup is the biggest thing.
Any help would be appreciated. I'm sure its something easy. I just can't wrap my mind around the logic.
You could solve the issue by checking all inputs each time you call the handler and set a var to true, if there is a match:
let matches = false;
$('input[name="item_color[]"]').each(function() {
if ($(this).val().match(regx)){
matches = true;
}
});
Furthermore the issue, that you mentioned in the comments, that the event handler isn't working when you define it outside the add handler, is related to the fact, that the inputs aren't created at the time of the definition. To prevent it you could attach the event listener directly to the body but add a selector to it:
$('body').on('keyup', 'input[name="item_color[]"]', function() {
Then the event listener is attached to an element that exists and the selector is used not before the listener is called.
Working example:
$("#add").click(function(){
$('#input-wrapper').append('<input name="item_color[]">');
});
$('body').on('keyup', 'input[name="item_color[]"]', function() {
let matches = false;
var regx = /(blue|red|orange)/gmi;
$('input[name="item_color[]"]').each(function() {
if ($(this).val().match(regx)){
matches = true;
}
});
if (matches){
$("#divcolor").show();
}
else {
$("#divcolor").hide();
}
});
#divcolor {
display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="add">Add</button>
<div id="input-wrapper">
<input name="item_color[]">
</div>
<div id="divcolor">
<p>div visible</p>
</div>

Localstorage getitem - match to div class

So I have created a simple code, so when the user clicks a child div of 'speaker-cookie' parent, they then set a localstorage value. Code is:-
$(".speakers-cookie div").on( "click", function() {
var speakerpop = $(this).attr("class");
localStorage.setItem('speaker', speakerpop);
});
This is working well, when on another page I want to get the value for the speaker and test IF the value matches a div, then change the colour of the div. I have tried the following:-
<script>
var speakercolor = localStorage.getItem("speaker");
$('body').find(speakercolor).css('background','red')
</script>
Could someone please advise what I am doing wrong here? This is not colouring the div atall.
Thank you

Transverse Html Elements Till a Specifc Attribute (id) using Jquery

I am using Jquery 1.7.2.
I want to transverse Html Elements Till a Specifc Attribute (id) using Jquery on
mouse over on any html element in my page.
we have parents() function but problem is how to select stop on the parent element which has id attribute
$("*", document.body).click(function (e) {
e.stopPropagation();
var domEl = $(this).get(0);
var parentEls = $(domEl).parents()
.map(function () {
return this.tagName;
})
.get().join(", ");
$("b").append("" + parentEls + "");
});
this is code but i am getting all element till root
but i want to stop on a closet elements which has attribute id in the tag
Please help me out .
Just use closest:
$(this).closest('#the-id');
Unless your'e just looking for the closest one that has any id attribute, which would be:
$(this).closest('[id]');
Edit: after seeing your updated question, this should be what you want:
$(document).click(function(e) {
e.preventDefault();
var parents = $(e.target).parentsUntil('[id]')
.map(function() { return this.tagName; }).get().join(',');
console.log(parents);
});
Note that this approach accomplishes what you want without selecting and binding click events to every node in the DOM, which is a pretty heavy handed approach.
Edit (again): looks like maybe you wanted to include the tag with the id attribute on it (the above solution is everything up to, but not including that tag). To do this, the solution is pretty similar:
$(document).click(function(e) {
e.preventDefault();
var $parents = $(e.target).parentsUntil('[id]');
var tagNames = $parents.add($parents.parent())
.map(function() { return this.tagName; }).get().join(',');
console.log(tagNames);
});
It looks like you want to map the hierarchy from the clicked element up to the document root. In that case, you can apply parents() to event.target:
$(document).click(function(e) {
e.preventDefault();
var parentEls = $(e.target).parents().map(function() {
return this.tagName;
}).get().join(", ");
});
Note that, as jmar777, you should also change your selector: "*" adds an event handler to all the elements, which is probably not what you want. Bind a single handler to document instead to take advantage of event bubbling.

Why does not jQuery.live function work with static elements?

I have a dynamic HTML table, where I can add and remove rows.
Each row contains a button that has a class removeRow.
In my JavaScript, I have:
$('button.removeRow').live("click", function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
The problem is that it works for all buttons that belong to rows that were inserted after the page was loaded (by clicking on 'Add row' button).
It works for existing buttons, only if I change the above code to (but then it does not work for dynamically added rows):
$('button.removeRow').click(function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
I think that the live function should work for both, so can you point me into the right direction? Where can it go wrong?
OK I found a bug today. Somewhere in my code I had:
$('input[type=submit], button').click(function () {
return false;
});
I wanted it to work with the submit button, so it would not submit the form on click. I do not remember why I put button there. Anyways, because of that my static button clicks were attached this event, while dynamically created ones were not. Therefore live 'click' worked for dynamic buttons. Stupid mistake...
Hacky solution: Do both
$('button.removeRow').live("click", function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
and
$('button.removeRow').click(function () {
var row = $(this).parents('tr')
row.remove();
return false;
});
It would be helpful if you posted some example HTML as well as the code responsible for inserting new rows, though.
Maybe something is going wrong if other tr elements are matched by your .parents() selector. Try .closest():
$('button.removeRow').live("click", function(){
$(this).closest('tr').remove();
return false;
});
The live should work for both dynamic and pre-rendered elements.
I'd start by working out if that content really exists before that jQuery is run...Try outputting the result of the following somewhere, or use the debugger keyword, or even the dreaded alert:
$('button.removeRow').length
// The rest of your click handler definition...

Is it possible to distinguish between click and selection?

I have a div with a hidden child. Clicking in the div will toggle the visibility of the child. This works well.
Now the user wants to select some text in the child. Dragging the selection works but as soon as the mouse button is released, the div closes (because of the inClick handler).
If possible, I'd still like to be able to close the div from anywhere in the child because the child can be quite large (hundreds of lines, so it would be tedious to scroll to the div to toggle the child).
Needs to work with IE6+ and all sane browsers. I can't use jQuery directly :-( but I can copy code from jQuery so if jQuery had a solution, I clone it.
Suggestions?
You can do a check on window.getSelection() to see if it contains anything before closing your inner div.
For IE6 you'll want to substitute this with document.selection.
Note that this is proprietry to IE so you'll want to distinguish which method to use via object detection.
Working Demo
You could have a toggle control on the side of the DIV:
toggle.onclick = function () {
if ( this.className === 'closed' ) {
this.className = '';
content.style.display = '';
} else {
this.className = 'closed';
content.style.display = 'none';
}
};
Live demo: http://jsfiddle.net/HcVfW/