This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 8 years ago.
please help me out with this issue: both .click and .on are not working when i am clicking on appended
$(document).ready(function() {
$( ".cooldiv" ).click(function() {
alert(1);
});
$(".cooldiv").on('click', function(){
alert(1);
});
$("#fields_count").change(function() {
var $newDiv = $('<div class="cooldiv">i am cooldiv</div>');
//$($newDiv).addClass('cooldiv');
$("#testdivs").append($newDiv);
});
});
html is:
<div id="testdivs"><div class='cooldiv'>qwdqwdwef</div></div>
<input type="text" size="3" id="fields_count" name="fields_count" value="3">
when i am clicking on a div containing 'qwdqwdwef', alert comes, but it does not when clicking on appended div's of the same class.
Any ideas?
Try to use event-delegation, you may ask why should i use delegation here..? The answer is while binding events to the element with the class .cooldiv, it would not be available in the Dom. so event wont get bound to that. So we have to bye pass the situation by means of event delegation
$('#testdivs').on('click','.cooldiv',function(){
alert(1);
});
You need to use delegation. Because your new element was not there when you added the click event handler you need to use a delegated event handler.
Try this instead:
$(document).on('click', '.cooldiv', function(){
alert(1);
});
You might want to check out the jQuery documentation about .on().
You need event delegation.
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
try this:
$("#testdivs").on('click','.cooldiv', function(){
alert(1);
});
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
Suppose I have some jQuery code that attaches an event handler to all elements with class .myclass.
For example:
$(function(){
$(".myclass").click( function() {
// do something
});
});
And my HTML might be as follows:
<a class="myclass" href="#">test1</a>
<a class="myclass" href="#">test2</a>
<a class="myclass" href="#">test3</a>
That works with no problem.
However, consider if the .myclass elements were written to the page at some future time.
For example:
<a id="anchor1" href="#">create link dynamically</a>
<script type="text/javascript">
$(function(){
$("#anchor1").click( function() {
$("#anchor1").append('<a class="myclass" href="#">test4</a>');
});
});
</script>
In this case, the test4 link is created when a user clicks on a#anchor1.
The test4 link does not have the click() handler associated with it, even though it has class="myclass".
Basically, I would like to write the click() handler once and have it apply to both content present at page load, and content brought in later via AJAX / DHTML. Any idea how I can fix this?
I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.
From http://api.jquery.com/live/
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.
See http://api.jquery.com/on/
So instead of...
$(".myclass").click( function() {
// do something
});
You can write...
$('body').on('click', 'a.myclass', function() {
// do something
});
This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.
The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:
$('ul').on('click', 'li', function() {
alert( $(this).text() );
});
As long as the ul tag exists this will work (no li elements need exist yet).
Sometimes doing this (the top-voted answer) is not always enough:
$('body').on('click', 'a.myclass', function() {
// do something
});
This can be an issue because of the order event handlers are fired. If you find yourself doing this, but it is causing issues because of the order in which it is handled.. You can always wrap that into a function, that when called "refreshes" the listener.
For example:
function RefreshSomeEventListener() {
// Remove handler from existing elements
$("#wrapper .specific-selector").off();
// Re-add event handler for all matching elements
$("#wrapper .specific-selector").on("click", function() {
// Handle event.
}
}
Because it is a function, whenever I set up my listener this way, I typically call it on document ready:
$(document).ready(function() {
// Other ready commands / code
// Call our function to setup initial listening
RefreshSomeEventListener();
});
Then, whenever you add some dynamically added element, call that method again:
function SomeMethodThatAddsElement() {
// Some code / AJAX / whatever.. Adding element dynamically
// Refresh our listener, so the new element is taken into account
RefreshSomeEventListener();
}
Hopefully this helps!
Regards,
After jQuery 1.7 the preferred methods are .on() and .off()
Sean's answer shows an example.
Now Deprecated:
Use the jQuery functions .live() and .die(). Available in
jQuery 1.3.x
From the docs:
To display each paragraph's text in an
alert box whenever it is clicked:
$("p").live("click", function(){
alert( $(this).text() );
});
Also, the livequery plugin does this and has support for more events.
If you're adding a pile of anchors to the DOM, look into event delegation instead.
Here's a simple example:
$('#somecontainer').click(function(e) {
var $target = $(e.target);
if ($target.hasClass("myclass")) {
// do something
}
});
You can bind a single click event to a page for all elements, no matter if they are already on that page or if they will arrive at some future time, like that:
$(document).bind('click', function (e) {
var target = $(e.target);
if (target.is('.myclass')) {
e.preventDefault(); // if you want to cancel the event flow
// do something
} else if (target.is('.myotherclass')) {
e.preventDefault();
// do something else
}
});
Been using it for a while. Works like a charm.
In jQuery 1.7 and later, it is recommended to use .on() in place of bind or any other event delegation method, but .bind() still works.
Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
link text
$(function(){
$(".myclass").live("click", function() {
// do something
});
});
If your on jQuery 1.3+ then use .live()
Binds a handler to an event (like
click) for all current - and future -
matched element. Can also bind custom
events.
You want to use the live() function. See the docs.
For example:
$("#anchor1").live("click", function() {
$("#anchor1").append('<a class="myclass" href="#">test4</a>');
});
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
Suppose I have some jQuery code that attaches an event handler to all elements with class .myclass.
For example:
$(function(){
$(".myclass").click( function() {
// do something
});
});
And my HTML might be as follows:
<a class="myclass" href="#">test1</a>
<a class="myclass" href="#">test2</a>
<a class="myclass" href="#">test3</a>
That works with no problem.
However, consider if the .myclass elements were written to the page at some future time.
For example:
<a id="anchor1" href="#">create link dynamically</a>
<script type="text/javascript">
$(function(){
$("#anchor1").click( function() {
$("#anchor1").append('<a class="myclass" href="#">test4</a>');
});
});
</script>
In this case, the test4 link is created when a user clicks on a#anchor1.
The test4 link does not have the click() handler associated with it, even though it has class="myclass".
Basically, I would like to write the click() handler once and have it apply to both content present at page load, and content brought in later via AJAX / DHTML. Any idea how I can fix this?
I am adding a new answer to reflect changes in later jQuery releases. The .live() method is deprecated as of jQuery 1.7.
From http://api.jquery.com/live/
As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live().
For jQuery 1.7+ you can attach an event handler to a parent element using .on(), and pass the a selector combined with 'myclass' as an argument.
See http://api.jquery.com/on/
So instead of...
$(".myclass").click( function() {
// do something
});
You can write...
$('body').on('click', 'a.myclass', function() {
// do something
});
This will work for all a tags with 'myclass' in the body, whether already present or dynamically added later.
The body tag is used here as the example had no closer static surrounding tag, but any parent tag that exists when the .on method call occurs will work. For instance a ul tag for a list which will have dynamic elements added would look like this:
$('ul').on('click', 'li', function() {
alert( $(this).text() );
});
As long as the ul tag exists this will work (no li elements need exist yet).
Sometimes doing this (the top-voted answer) is not always enough:
$('body').on('click', 'a.myclass', function() {
// do something
});
This can be an issue because of the order event handlers are fired. If you find yourself doing this, but it is causing issues because of the order in which it is handled.. You can always wrap that into a function, that when called "refreshes" the listener.
For example:
function RefreshSomeEventListener() {
// Remove handler from existing elements
$("#wrapper .specific-selector").off();
// Re-add event handler for all matching elements
$("#wrapper .specific-selector").on("click", function() {
// Handle event.
}
}
Because it is a function, whenever I set up my listener this way, I typically call it on document ready:
$(document).ready(function() {
// Other ready commands / code
// Call our function to setup initial listening
RefreshSomeEventListener();
});
Then, whenever you add some dynamically added element, call that method again:
function SomeMethodThatAddsElement() {
// Some code / AJAX / whatever.. Adding element dynamically
// Refresh our listener, so the new element is taken into account
RefreshSomeEventListener();
}
Hopefully this helps!
Regards,
After jQuery 1.7 the preferred methods are .on() and .off()
Sean's answer shows an example.
Now Deprecated:
Use the jQuery functions .live() and .die(). Available in
jQuery 1.3.x
From the docs:
To display each paragraph's text in an
alert box whenever it is clicked:
$("p").live("click", function(){
alert( $(this).text() );
});
Also, the livequery plugin does this and has support for more events.
If you're adding a pile of anchors to the DOM, look into event delegation instead.
Here's a simple example:
$('#somecontainer').click(function(e) {
var $target = $(e.target);
if ($target.hasClass("myclass")) {
// do something
}
});
You can bind a single click event to a page for all elements, no matter if they are already on that page or if they will arrive at some future time, like that:
$(document).bind('click', function (e) {
var target = $(e.target);
if (target.is('.myclass')) {
e.preventDefault(); // if you want to cancel the event flow
// do something
} else if (target.is('.myotherclass')) {
e.preventDefault();
// do something else
}
});
Been using it for a while. Works like a charm.
In jQuery 1.7 and later, it is recommended to use .on() in place of bind or any other event delegation method, but .bind() still works.
Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
link text
$(function(){
$(".myclass").live("click", function() {
// do something
});
});
If your on jQuery 1.3+ then use .live()
Binds a handler to an event (like
click) for all current - and future -
matched element. Can also bind custom
events.
You want to use the live() function. See the docs.
For example:
$("#anchor1").live("click", function() {
$("#anchor1").append('<a class="myclass" href="#">test4</a>');
});
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
Why is the link not working if the link is created with javascript?
It only works if I make the link without the html() output
Not working
$(".link").on('click', function(){
alert('Hello');
});
$("#link").html('Link');
<div id="link"></div>
Working
$(".link").on('click', function(){
alert('Hello');
});
Link
Your code doesn't work because event is bound when the element does not exists in DOM
Wrap your code in ready or move the code to the bottom of body so your code will run when the DOM is completely parsed
Use event delegation to bind event on dynamically created elements.(This will make the first option above optional)
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$(document).ready(function() {
$("#link").on('click', '.link', function() {
$("#link").append(' Link ');
});
$("#link").html('Link');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="link"></div>
Change the order of the calls. The element with class of .link does not exist in the DOM yet when you attach the handler. You must add the link via the html call on the div before you can attach a handler to it with the on method. See below for a complete, working example.
$("#link").html('Link');
$(".link").on('click', function(){
alert('Hello');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="link"></div>
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
I am making dynamic buttons using jQuery. Now I want to use this buttons as any other buttons. Here is my HTML:
<label class='twobuttons'><div id="submit-button" >GO!</div></label>
<div id='result'></div>
And here is my JavaScript:
$(document).ready(function(){
$('#submit-button').click(function(){
$('#result').append("<label><div id='share' class='longbutton'>Share this route</div></label>");
$('#result').append("<label><div id='goback' class='longbutton'>Create another one !</div></label>");
});
$('#share').on("click",function(){
alert('hi');
});
$('#goback').on("click",function(){
alert('hello');
})
});
I'm specifically having trouble with the $('#share').on( part.
I tried the on() function as suggested here. But it is not working. Here is the fiddle of my code. Please correct me if I am wrong somewhere.
That isn't how .on() works, if you are dynamically creating elements, you can't bind an event handler to it, because at the point the code runs (document.ready), the element doesn't exist. So to "get around" that, you bind the event to a parent element (that exists) and then add the actual element you'll be clicking on as a parameter like this:
$('body').on("click", "#share", function(){
alert('hi');
});
$('body').on("click", "#goback",function(){
alert('hello');
})
DEMO
You should setup event delegation on #result instead, because by the time you're trying to setup the click handlers on #share, the element itself has not been added yet.
$('#result').on('click', '#share', function() {
// your code here
});
Try not to bind the event handler to $(document) by default; the closest element that will not get removed is the prime candidate.
Alternatively, only bind the click handlers after you've added the new elements.
Update
You're appending elements with a fixed identifier at every click of your button; note that identifiers should be unique per document, so you should make sure that the action is performed at most once.
The way the .on() method works changes according to how you use it. In your example the .on() method behaves similar to bind and will only work on elements that already exist.
Try this:
$(document).on("click",'#share',function(){
alert('hi');
});
DEMO
It's not enough to use .on(). You have to use event delegation with an element (such as document) that existed before your dynamically-created elements:
$(document).on('click', '#share', function () {
alert('hi');
});
(Based on your fiddle, you can use #result instead of document.)
Fiddle
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
jQuery 1.7 - Turning live() into on()
I used to love the .live() function that jQuery had. You would add it and voila, any future elements that matched the identifier would have that function.
Then it got deprecated and it was advised to use .on(). But it doesn't work. Below is my code that is placed in $(document).ready().
This works
$('#membership_number').live('change',function(e) {
alert("VALUE CHANGED");
});
This doesn't
$('#membership_number').on('change',function(e) {
alert("VALUE CHANGED");
});
Is there another way to achieve the same effect as .live() or am I just not using .on() correctly?
You have to subscripe the event to parent item and give selector to which you want to bind. If you do not want to give parent you can use document. Read more about on here
$(document).on('change', '#membership_number',function(e) {
alert("VALUE CHANGED");
});
OR
$('#parentId').on('change', '#membership_number',function(e) {
alert("VALUE CHANGED");
});
When handling dynamic elements in jQuery 1.7 +, you're using the on selector. It expects the event to be bound to a static element that is ready and available at page load, so the event can properly bubble up the chain and fire when the parent element is found.
$(document).on('change', '#membership_number', function(e){
alert("VALUE CHANGED");
});
You need to use a parent element to attach the handler. E.g. the document.
$(document).on('change', '#membership_number', function(e) {
alert("VALUE CHANGED");
});
You need to bind .on() at an ancestor element due to the way in which the event bubbles up until it matches the selector. This can be anything in the DOM that is an ancestor of the element you want the event(s) bound to.
You can of course use the ultimate ancestor, the document. For example:
$(document).on('change', '#membership_number', function(){});
.live() actually did this behind the scenes by binding an event on the document which was then filtered on the correct element. It is more efficient and practical to use an element as local as possible to the one you want an event on. For example if I wanted a click event on <li> elements where some <li> are added dynamically, I would bind the event to the parent <ul> and filter on the <li> like so:
$('ul').on('click', 'li', function(){});
This is also more efficient than binding a separate click event on each <li>.