Detect change in div and do rebind events jQuery - javascript

In jQuery how can I watch a div to determine if it has changed so that I can rebind events and perform some other action as needed?

If the div has dynamic content I would like to tell you about event delegation.
Event delegation allows you to avoid adding event listeners to
specific nodes; instead, the event listener is added to one parent.1
To use event delegation in jQuery you use the on method and provide a selector argument.

You could use DOMSubtreeModified event(see here)
$('my-selector').bind('DOMSubtreeModified', function() {
console.log('Children have been modified');
});
I haven't checked the supported nature of this event but in chrome it works.
Unfortunately : Why is the DOMSubtreeModified event deprecated in DOM level 3?

Related

Js click property not working on html loaded by js

I have created a dynamic page in which i am loadin 10 element by default. after that if user scroll doun i am apppending more element to this page by js (appending data by ajax).
and on click of a tag i am doing some js work
I am using
$('.atnd_modal').click(function(){
alert("dsfds");
});
not
onclick ="function()" and i dont want to do that onclick.
Problem i am facing that this js is working perfectely for first 10 result but after that it stop working for the block i have appended by js.
how can to do it working for both the cases ??
Try jquery on() for event delegation. It will work on dynamic loaded element on DOM also.
$('body').on('click','.atnd_modal', function(){
alert("dsfds");
});
Delegated events have the advantage that they can process events from
descendant elements that are added to the document at a later time.
Your click event is not working because when you use click() it will attach this handler to all elements having atnd_modal class, but when new element loading in DOM that event is not attached automatically with new element. For previous elements it will work fine but for new element it won't. So here comes Delegated events. We shall attach event to parent element with on() or delegate()
If you want to bind an event to the dynamically added new elements you have to use event delegation :-
Delegated events 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.
Change your code like this, use Jquery On
$('body').on('click','.atnd_modal', function(){
alert("dsfds");
});

Event stops working after dynamic ul li changes

The Code:
if($('.info-dropdown').length){
setTimeout(function(){
$('li').has('input[type="checkbox"]').on('click', function(){
$(this).find('.brand-checkbox').parent().toggleClass('active');
});
}, 10);
}
The Problem: This code detects event click on element checkbox. After dynamically changing this ul li the event stops working.
Note: These checkboxes are from bootstrap dropdown menu.
To bind event for dynamic HTML, You can follow below code :
$('containerSelector').on('eventName', 'mainElementSelector' function(e){
});
Realtime example
$("ul").on("click", "li:has(:checkbox)", function(){
});
Event handlers added directly to an object are added only to that specific DOM object. If you then add or replace more DOM objects, those DOM object won't have any of these event handlers on them. You will have to either manually add the event handlers after you create or replace the DOM objects or you will have to switch to using delegated event handling.
Delegated event handling attaches the event handler to a common parent object (that is not replaced) and uses the fact that many events bubble up the parent chain in order to process the event from the common parent. This allows you to freely create or replace child elements, but still have one event handler that works for all child objects.
You can read a lot more about how to do delegated event handling in these other answers:
jQuery .live() vs .on() method for adding a click event after loading dynamic html
Does jQuery.on() work for elements that are added after the event handler is created?
JQuery Event Handlers - What's the "Best" method
As illustrated in those referenced answers, the general idea is like this:
$("#staticParentSelector").on("click", ".selectorForDynamicChildren", function(e) {
// event handler code here
});

jQuery On event Off unbind automatically

Is there a way to automatically unbind all "on" events that were set on an element? I have found a solution but i don't know if it is the corect one.
$(document).off('click', 'li').on('click', 'li', function(e){
e.preventDefault();
// some stuff goes here
});
EDIT:
I have tried all the suggested answers but none worked as i wanted. Maybe it was my mistake that i didn't give enough information: the point is that all my content is loaded dynamically like in tabs and some tabs could be loaded more time.
I have tried this $('li').off().on('click', function(){
});
-> did not work
Also have tried this $('li').unbind().on('click', function(){
});
-> did not work.
You can call .unbind() without parameters to do this:
$('li').unbind();
From the docs:
In the simplest case, with no arguments, .unbind() removes all handlers attached to the elements.
As of jQuery 1.7, off() and on() are the preferred methods to bind and unbind event handlers.
So to remove all handlers from an element, use this:
$('li').off();
or for specific handlers:
$('p').off('click hover');
And to add or bind event handlers, you can use
You can just use unbind() or off() to remove all event handlers from an object.
$('#myNode').unbind();
off() is preferred way to do this in jQuery 1.7+ (noted by #Krishna).
$('#myNode').off();
JSFiddle
$('li').off();//Remove all event handlers from all li elements:
$('li').off('click');//Remove specific event - click
From documentation .off(),
The .off() method removes event handlers that were attached with .on().
From .unbind() documentation,
As of jQuery 1.7, the .on() and .off() methods are preferred to attach and remove event handlers on elements.
$('li').unbind(); //removes all event handlers
$('li').unbind('click');//removes specific event - click

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.

Global jQuery `.click()`

I would like to fire an event when anything on the page is clicked, and then process normally. For example a click would be fired, I would see if the target matched something, alert if it did, and then have the click event continue (no preventDefault()).
$(document).click(function(e) {
// e.target is the element which has been clicked.
});
This will handle all click events unless a handler prevents the event from bubbling up (by calling the stopPropagation() method of the event object).
$("body").click(function (event) {
// Your stuff here
}
3 options for you:
This is how .live() in jquery works. Everything bubbles to the top, and it matches the selector you set.
http://api.jquery.com/live/
A more efficient way to do it is using .delegate, or providing a context to .live() so you don't have to bubble to the top.
http://api.jquery.com/delegate/
If you want to do it manually, bind 'click' to the document, and use .closest() to find the closest matching selector:
http://api.jquery.com/closest/
It's all the same concept, event delegation as mentioned already.

Categories

Resources