Performing an action on Parent/Child elements independently - javascript

I have HTML similar to the following in my page
<div id="someDiv">
<img src="foo.gif" class="someImg" />
</div>
The wrapper div is set up such that when it is clicked, it's background-color changes using the following jQuery code.
$("div").click(function(event){
$(this).css("background-color", "blue");
});
I also have some jQuery associated with my img that will do some other function (for the sake of argument I am going to display and alert box) like so:
$("img[class=someImg]").click(function(event){
alert("Image clicked");
});
The issue I have come across is that when I click on the img, the event associated with the div is also triggered. I'm pretty sure that this is due to the way that jQuery (or indeed JavaScript) is handling the two DOM elements - clicking the img would require you to also technically click the div, thus triggering both events.
Two questions then really:
Is my understanding of the
DOM/JavaScript flawed in some way or
is this actually how things are
occurring?
Are there any jQuery methods that
would allow me to perform actions on
a child element without invoking
those associated with its parent?

That is known as event bubbling, you can prevent it with stopPropagation():
$("img[class=someImg]").click(function(event){
alert("Image clicked");
event.stopPropagation();
});
.
Is my understanding of the DOM/JavaScript flawed in some way or
is this actually how things are
occurring?
That is because of what is known event bubbling.
Are there any jQuery methods that would allow me to perform actions
on a child element without invoking
those associated with its parent?
Yes, you need stopPropagation()

No, this is by design. Events bubble up through the entire dom, if you put another handler on body, it would fire too
Yes :) JQuery normalizes the event object, so adding event.stopPropagation() in your img click handler will give you the behavior you expect on all browsers

The problem you just facing is called "event bubbling". That means, if you click on a nested
element, that click event will "bubble up" the DOM tree.
If other elements also are bound to an click event, their listeners will fire aswell.
Solution to prevent this is called:
stopPropagation()
which is used within your event handler
$("img[class=someImg]").click(function(event){
event.stopPropagation();
alert("Image clicked");
});

This is what's called event bubbling, and you can stop it to get the behavior you want with .stopPropagation() (or return false; if you want to stop the event completely, including handlers on the same level), like this:
$("img[class=someImg]").click(function(event){
alert("Image clicked");
event.stopPropagation();
});
You can view a demo here, comment it out and click run again to see the difference.
The short version is that when most event types happen, they happen on the immediate element, then bubble up the DOM, occurring on each parent as they go. This is not jQuery specific at all, native JavaScript does this. If you're more curious, I'd read the linked article, it has a great explanation of what's going on.

Related

In jQuery, how can I replace the body of my document and still get JavaScript to fire?

Currently, my page has a top navigation bar.
When clicking, the page currently does a full reload which causes a flickering effect.
To avoid this, I'm planning to use the jQuery html function to just replace the main body of the page and leave the header intact.
But this appears to stop JavaScript function from running on the main body of the page.
Is there a way I can use the jQuery html function and still get my JavaScript to work on the HTML elements in the body?
You can use event bubbling to listen to the events on document, and based on the target element, execute appropriate event handling logic.
jQuery makes it easier to register such event handlers by simplifying the logic around identification of the target element. The syntax for registering such an event handler would be: $(document).on(events, selector, handler).
These are called Delegated Event Handlers in jQuery's documentation:
Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.
I have illustrated an example in the snippet below. Notice how you do not need to re-register the event listener even after replacing the HTML content.
$(document).on("click", "#clickMe", function() {
alert("Element clicked.");
});
// Change the innerHTML after 10 seconds.
setTimeout(function() {
$(document.body).html(`
<div id="clickMe">[New] Click Me</div>
`);
}, 10000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="clickMe">Click me</div>
You can read more about event bubbling here and more about jQuery's event handling syntax here.
Note: In my opinion, you need to rethink your architecture. While the suggested approach works, given the unconventional nature of your architecture, you may run across other challenges in future.

Using jQuery delegate (on) with a check box causes huge delay in response - why?

Hi I have a dynamically create table which acts as a pick list using check boxes. I Want these check boxes to be mutually exclusive. So upon checking a box I need to clear any other checked boxes.
$(document).on("keydown", "#list_Instructors input.allocate",function(event){
alert("hit");
$("#list_Instructors input.allocate").removeAttr('checked');
$(event.target).attr('checked', 'checked');
});
This sort of works but there is a huge delay between clicking and anything happening which is no good. I have tried all sorts of combinations with no success.
Is there is simple explanation as to why this is creating a delay.
Your problem is you bind on method for whole DOM which is really BAD.
So always try to bind that to the closest div (closest parent element) which your controls are exist.
And second thing is always cache your selectors for better performance.Like below
var dataTable=$('#dataTable');
dataTable.on("click", function(event){
alert($(this).text());
});
About Event performance from Jquery API says like below.
Attaching many delegated event handlers near the top of the document
tree can degrade performance. Each time the event occurs, jQuery must
compare all selectors of all attached events of that type to every
element in the path from the event target up to the top of the
document. For best performance, attach delegated events at a document
location as close as possible to the target elements. Avoid excessive
use of document or document.body for delegated events on large
documents.
What you might be seeing is that until the alert box is dismissed, the code afterwards is not executed. The alert command is a blocking one.
Perhaps you can use console.log() for debugging purposes of this feature. This will not block your code and it will be executed on the keydown event.
You need to use $(this) instead of going through another lookup. Also as stated above try to bind to the closest parent element if possible, for example a container div. With that said this should speed you up a bit:
$(document).on('keydown', '#list_Instructors input.allocate', function (event) {
//alert("hit");
console.log('hit');
$(this).removeAttr('checked');
$(event.target).attr('checked', 'checked');
});
But you should try to replace document with a container div or another parent element

how to select the rest of a div?

i got a problem
<div id='parent'>
<div id='child'>
</div>
</div>
what i want is when the child is clicked addClass,and when the rest of parent is clicked removeClass,so when i try to do
$('#child').click(function(){
$(this).addClass();
})
$('#parent').click(function(){
$('#child').removeClass();
})
its not working i think its because the child is actually inside the parent,so when the child is clicked the parent clicked right?
so how can i do that?
try this:
$('#child').click(function(evt){
evt.stopPropagation();
$(this).addClass("myClass");
});
You could use event.stopPropagation to prevents the event from bubbling up the DOM tree, preventing any parent handlers from being notified of the event.
$('#child').click(function(e){
e.stopPropagation();
$(this).addClass();
});
Several users have already suggested a good solution - here's an explanation of why it works:
When you click an HTML element (actually a DOM object...), the click event "bubbles" all the way up to the root element. For example, a click in #child also triggers a click in #parent, as you expected.
To stop this behavior, you need to call .stopPropagation() on the click event - that will tell the browser that you do not want the event to propagate, but keep it "local". Basically, when you've handled it here, you're done with it and don't want to see it again.
Conveniently, jQuery event handlers take the event as the first argument, so if you assign any function with the signature function (e) { ... }, you can stop event propagation by e.stopPropagation(); as others have suggested. In your case, you want
$('#child').click(function(e){
$(this).addClass();
e.stopPropagation();
});
$('#parent').click(function(){
$('#child').removeClass();
});

What's the right mindset in using jQuery's event.stopPropagation()

I have two approaches in mind on how to apply jQuery's event.stopPropagation():
Optimistic approach - By default, all event handlers are without stopPropagation(). stopPropagation() would be added to a handler only if there's some unnecessary and undesired behaviour caused by event bubbling.
Pessimistic approach - By default, stopPropagation() is added to all event handlers. If there's some desired behaviour missing due to disconnected even bubbling, then the corresponding stopPropagation() would get removed.
I was wondering which one of the two, or neither, is the mindset I should have when utilizing stopPropagation() in my development. I am leaning more towards 2) because it looks like it would have better performance because unnecessary bubbling gets prevented. I would like to hear from experts on the topic.
Calling stopPropagation everywhere isn't good. It breaks event delegation*, is probably less efficient unless you literally add handlers to every single element on the page (and if you're doing that, you should be using event delegation), and you might not remember to do it.
So rule of thumb: Only call stopPropagation when you need to do so.
* That is, .live, .delegate, and the delegate version of .on.
Here's an example of event delegation, which relies on bubbling to listen for events that originate from elements added after the listener was created:
document.documentElement.addEventListener('click', function(e) {
if(e.target.nodeName === 'a') {
console.log('A link was clicked!');
}
});
Here's somebody throwing in jQuery that breaks that:
$('div').click(function(e) {
e.stopPropagation();
});
Any <a> that is a descendant of a <div> will no longer get its clicks handled! Please don't do this.
Call stopPropagation only if you realy need it. And remember, if you use jQuery live function and you stop it, live handler never calls, because live event stored in document element.

Adding event listeners to current and future elements with a particular class

With JQuery, is it possible to add an event listener to any element that currently, or will in the future, have a particular class?
I'm working on a project that makes heavy use of contentEditable, so the DOM is changing, and elements can have classes added and removed as a result of user input.
I would like to be able to say "elements of class X should do Y when clicked", but if I understand correctly, $(".X").click(Y) will only add the event listener to elements that currently have class X.
Furthermore, if an element is no-longer part of class X, then it will still have the click event listener.
How can I do this?
Yep. What you're talking about is called event delegation. Here's an example:
$('#container').on('click', '.innerElement', function(){
/// Do stuff
});
In your case, #container would be an element that is known to exist on page load which will contain the child elements you care about (either now or in the future). This approach takes advantage of event bubbling in the DOM.
As another poster mentioned, the live method will also work -- but it has been deprecated in jQuery 1.7, and is generally not as performant as using more selective delegation (such as the example above).
you'll want to use event delegation. jquery 1.7 has made this more abstract than previous versions, but it looks something like this:
$("#myWrappingElement").on("click", ".myclass", function(event){
alert($(this).text());
});
this basically adds a click event listener to the #myWrappingElement element, and jquery will automagically look to see what the original event target was and fire the proper function. this means you can add or remove .myclass elements and still have events fire on them.
the jQuery live() method swill allow to have a "live" action listener - so if new DOM elements match the selector, they will be attached to the action listener. For example:
$(".X").live("click", function(){
alert('some action');
});
See the documentation here for more info: http://api.jquery.com/live/
I'm not sure that the second part of your question about keeping the action listener attached after removing the class os possible - someone else might have a solution though.

Categories

Resources