Child's event is not fired when parent's HTML is changed - javascript

Here's an example http://jsbin.com/ukoqud/3/edit
If you click on a red box, you'll get an alert.
If you click on a link, everything in a blue box will be replaced with just a red box. Link will disappear and if you click on a red box then, you'll get no alert.
Why this happens?
Is it related to innerHTML?
Does it work the same way in all browsers?
Here's one more example http://jsbin.com/ukoqud/1/edit In this one you'll get an alert after clicking on a link. Things happen in a quite similar way, but result is different.
I would like to understand the reason, there's no need to fix my code.

When you call $(".red"), it returns a collection of DOM elements that exist at that moment. So $(".red").click(function...) just binds a handler to the click event on those elements. If you later create new elements with the same class, they weren't in this collection, so they don't have the handler bound to them. jQuery doesn't watch the DOM for changes and update the handlers dynamically -- the bindings are just on the elements you matched at the time you called click().
You either need to bind the handler again after adding the new HTML, or use delegation with .on():
$(".blue").on("click", ".red", function(){
alert('click on a red box detected');
});
This works by binding a handler to $(".blue"), which doesn't change dynamically. The handler checks whether the element you clicked on matches the ".red" selector, so it's able to handle dynamically-added elements without requiring rebinding.
I think the reason why it works in your second example is because the red block isn't inside the blue box to start. When you move it inside, jQuery reuses the same DOM elements, so the bindings go along with it. In the first example, the red box starts out inside the blue box. When you do $('.red').parent().html(...), the first thing it does is empty $('.red').parent() (the blue box), so the original red element is removed from the DOM, and its bindings are lost.

We need to understand how setting html of an element works. Then you will figure out your answer yourself.
Take a look at this bin Updated Bin
When we set HTML of an element, it first removes all the elements inside it.
Those elements are not removed from memory depending upon whether they are garbage collected or not.
If any of the child is having a reference, then that particular child won't be garbage collected.
In your case, we are having a reference to red element so it is still present in memory but not a part of document.
When we say blue.html(red) in my example, red element becomes a part of document again but this time there won't be any handlers on it So your click does not work.
While in your example2,
red element is always a part of document hence no handlers were lost when red element is moved inside blue element.
I hope this will help.

because when u click the link, you delete everything on screen and create everything from a scratch and event binding goes away. so you should use this
$(".blue").on("click", ".red", function(){
alert('');
});
this way, binding is done differently. it doesnt bind it statically

Related

Detach then Append Div

I have been working with this script and its mind boggling as it looks as though it should work correctly, however it is not. So I turn to you all for an extra set of eyes on what I am missing.
Situation: Basically, what I am trying to do is on click detach a div, then when another radio button is selected, append the div back to its position.
I have included a JSFiddle so you can see that I may not be entirely off track : http://jsfiddle.net/heykate/pusk6ezx/
On load, the user is presented with two options, Support or Inflatable with the default size selected on the support size with the other models sizes hidden. Which is fine. I know ultimately I want to change that first line of code from hide() to detach().
Once I go to click on the second style option, it shows the second models widths like it is supposed to, however if I was to switch back to the first style option. The div I originally detached, is still hidden and will not .append() within my code.
Here is what my script looks like:
$(document).ready(function(){
$('#5e8a1520d82ed2834919fda63f4a3f84').hide();
$('input[type="radio"]').change(function(){
if($(this).attr("value")=="489"){
$( "#b6304c97422f08727702021e2c6c7cda" ).append( ".rightCol" );
$("#5e8a1520d82ed2834919fda63f4a3f84").detach();
}
if($(this).attr("value")=="488"){
$("#b6304c97422f08727702021e2c6c7cda").detach();
$("#5e8a1520d82ed2834919fda63f4a3f84").show();
}
});
});
Please let me know what I am missing. Basically the reason I am doing this to begin with is
To make it less confusing on the front end and
because the defaults are set (for both sizes) they get mashed up in the product order info, so if I could clear the other widths checked radio button or detach and prevent it from being seen, I think it would work out just fine.
.detach REMOVES the element from the DOM. Since it's no longer in the DOM, when you try to .show() it later, it's no longer in the dom, and therefore not findable/usable. That's why .detach() returns the node you've removed, in case you want to re-use it:
foo = $('#blahblah').detach(); // 'foo' now contains the detached now
$('#otherplace').attach(foo); // reinsert the foo element we detached.
//OR
$('#otherplace').append(foo);

Attaching multiple click events without having to repeat myself

Here is the fiddle.
Ignore the styling, that's not important.
Basically I needed to open the Fancybox with two links present, but I only want one gallery image. I figured that out easily enough. When the thumbnail is clicked it triggers the li anchor.
To keep the galleries separate I did unique classes for each ol.
The problem I have run into is I will be repeating myself.
I attempted to do a loop (commented out), but the logic is beyond my grasp.
What is the best way to attach a new click handler (I need to add 8 more) without repeating myself in my current fashion? I've also tried a function with a couple parameters, but I had trouble with the e.preventDefault().
I greatly appreciate any guidance, thanks!
This looks like a great use case to use jQuery's on() method. on() is a method that will allow you to establish a handler on an outer container that can listen to its children for click events. So, for example: if you specified a class of .js-listen on your lists, you could call on() like this:
$('.js-listen').on('click', 'other-selector', function(e){
// function logic with either $(this) or e.target goes here
}
This block would essentially look for all elements with .js-listen and then when something inside the element with the .js-listen class is clicked, the event will bubble up through the DOM and the event will be handled according to the element that was clicked. The second parameter I have 'other-selector' can be a class name, element, or ID. so you could essentially put something like img there and it would fire the event if the child element clicked was an <img> tag.
This prevents you from attaching a handler a million times, and one of the benefits of on() is that if elements are dynamically added to the container with the handler, you don't have to worry about attaching handlers to those elements, because again, they bubble up!
Hope this helps!

Handle stuff after dom changes

I've got a page with some Javascript / jQuery stuff, for example:
(function()
{
$('.tip').tooltip();
$('.test').click(function()
{
alert('Clicked!')
});
}();
On the page I insert some HTML with jQuery so the DOM changes. For example, I insert a extra element with the class "tip" or "test". The just new inserted elements doesn't work because jQuery is working with the non-manipulated DOM and the just inserted elements aren't there. So I've searched around and came to this solution for the "click":
$('body').on('click','.click',function()
{
alert('Clicked!')
});
I don't understand why, but this way it's working with the manipulated DOM and the jQuery stuff works on the new inserted elements. So my first question is, why does this work and just the click() function not? And the second question, why do I have to point to the "body"?
Finally, my third question is, how get this done with the tooltip?
I know that there is so many information about this subject (previous the delegate() and live() function I've read) but I can't found a explanation about it. And I can't get my third question solved with the information I found.
I'm looking forward to your responses!
Extra question:
4) Is it recommended to point always to the "body" for this kind of situations? It's always there but for possible performance issues?
So my first question is, why does this work and just the click()
function not?
Because the event handler is now delegated to a parent element, so it remains even after replacing/manipulating child elements.
Ancient article on event delegation for your perusal - but the concepts remain the same:
http://www.sitepoint.com/javascript-event-delegation-is-easier-than-you-think/
And the second question, why do I have to point to the "body"
You don't, any suitable parent element will do. For example, any direct parent (a div wrapper, for instance) which does not get replaced.
Finally, my third question is, how get this done with the tooltip?
You need to re-initialize your tooltip plugin on the newly inserted elements. For example:
$.get("foo.html", function (html) {
$("#someDiv").html(html);
$("#someDiv").find(".tip").tooltip();
});
The click() event doesn't work when you manipulate the DOM because JQuery is not watching for DOM changes. When you bind the click() event it is selecting the elements that are on the page at that time. New ones are not in the list unless you explicitly bind the event.
Because you have pointed the click() event on the body. JQuery then checks to see if the target of the click matches any of the event handlers (like what you have created) match the element clicked. This way any new elements will get the event 'associated' with them.
Because the tooltip isn't an event that you can place on the body, you will need to re-initialize it when the element is created.
EDIT:
For your fourth question, is it depends. The advantage of binding to the body is that you don't accidentally bind an event to an element more than once. The disadvantage is that you are adding event handlers that need to be checked on each event and this can lead to performance issues.
As for your concerns about DRY, put the initialization of the tooltips into a function and call that when you add them. Trying to avoid having the same function call is a little overkill in this regard, IMO.
Events are bound to the specific object you are binding it to.
So something like $('.tip').tooltip() will perform the tooltip() functionality on $('.tip') which is actually just a collection of objects that satisfies the css selector .tip. The thing you should take note of is, that collection is not dynamic, it is basically a "database" query of the current page, and returns a resultset of HTML DOM objects wrapped by jQuery.
Therefore calling tooptip() on that collection will only perform the tooltip functionality on the objects within that collection, anything that was not in that collection when tooltip is called will not have the tooltip functionality. So adding an element that satisfies the .tip selector, after the tooltip() call, will not give it the tooltip functionality.
Now, $('body').on('click','.click', func) is actually binding the click event to the body tag (which should always exist :P), but what happens is it captures whether the click event has passed through an element your target css selector (.click in this case), so since the check is done dynamically, new elements will be captured.
This is a relatively short summary of what's going on... I hope it helped
UPDATE:
Best way for your tooltip thing is to bind tooltip after you have added elements, e.g.
$('#container').load('www.example.com/stuff', function() {
$('.tip', $(this)).tooltip();
});

JQuery click anywhere except certain divs and issues with dynamically added html

I want this webpage to highlight certain elements when you click on one of them, but if you click anywhere else on the page, then all of these elements should no longer be highlighted.
I accomplished this task by the following, and it works just fine except for one thing (described below):
$(document).click(function() {
// Do stuff when clicking anywhere but on elements of class suggestion_box
$(".suggestion_box").css('background-color', '#FFFFFF');
});
$(".suggestion_box").click(function() {
// means you clicked on an object belonging to class suggestion_box
return false;
});
// the code for handling onclicks for each element
function clickSuggestion() {
// remove all highlighting
$(".suggestion_box").css('background-color', '#FFFFFF');
// then highlight only a specific item
$("div[name=" + arguments[0] + "]").css('background-color', '#CCFFCC');
}
This way of enforcing the highlighting of elements works fine until I add more html to the page without having a new page load. This is done by .append() and .prepend()
What I suspected from debugging was that the page is not "aware" of the new elements that were added to the page dynamically. Despite the new, dynamically added elements having the appropriate class names/IDs/names/onclicks ect, they never get highlighted like the rest of the elements (which continue to work fine the entire time).
I was wondering if a possible reason for why my approach does not work for the dynamically added content is that the page is not able to recognize the elements that were not present during the pageload. And if this is a possibility, then is there a way to reconcile this without a pageload?
If this line of reasoning is wrong, then the code I have above is probably not enough to show what's wrong with my webpage. But I'm really just interested in whether or not this line of thought is a possibility.
Use .live to "Attach a handler to the event for all elements which match the current selector, now and in the future". Example:
$(".suggestion_box").live("click", function() {
// means you clicked on an object belonging to className
return false;
});
Also see .delegate, which is similar.
Since the .live() method handles events once they have propagated to the top of the document, it is not possible to stop propagation of live events. Similarly, events handled by .delegate() will always propagate to the element to which they are delegated; event handlers on any elements below it will already have been executed by the time the delegated event handler is called.
from the jQuery documentation =)
(only to explain better why #karim79 also suggested the delegate method ;P )

Is there a onselect event for non-form elements?

Say I want to hide a span when the user highlights a bit of text containing that span, with the intention of copying that text on to his clipboard.
For example:
<p>The dragon <span class="tooltip">a large, mythical beast</span> belched
fire at St. George.</p>
I have found that in Firefox Mac, span.tooltip will disappear from view (in accordance with my CSS declarations) but will show up in the clipboard when it's copied there. I figured (wrongly?) that if I said "onHighlight, hide tooltip," maybe this wouldn't happen.
Though it may be more complicated, why not just have an onmousedown event on the <p> element, and thet event will then attach an onmousemove event and onmouseout event, so that if there is a mouse movement, while the button is down, then remove the class on the span elements, and once the user exits, the element then you can put them back.
It may be a bit tricky, and you may want to also look for key presses, or determine other times you want to know when to put back the css classes, but this would be one option, I believe.
It sounds like you need to go one step further and on highlight, remove the <span> and save a reference to it. Once the highlight is finished, re-insert the reference to the object.
// copy start detected
var savedTooltip = $('.tooltip').remove();
// later that day when copy finished
$('p').append(savedTooltip);
If position of the <span> in your markup is important, you'd have to create a temporary reference element so you'd know where to re-insert it in the DOM.

Categories