Event binding on dynamically created elements?
I have a bit of code where I am looping through all the select boxes on a page and binding a .hover
event to them to do a bit of twiddling with their width on mouse on/off
.
This happens on page ready and works just fine.
The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.
I have found this plugin (jQuery Live Query Plugin), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.
javascript jquery events unobtrusive-javascript
locked by Yvette Colomb♦ Jun 22 at 16:24
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
comments disabled on deleted / locked posts / reviews |
I have a bit of code where I am looping through all the select boxes on a page and binding a .hover
event to them to do a bit of twiddling with their width on mouse on/off
.
This happens on page ready and works just fine.
The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.
I have found this plugin (jQuery Live Query Plugin), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.
javascript jquery events unobtrusive-javascript
locked by Yvette Colomb♦ Jun 22 at 16:24
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
11
Here's a detailed article on how to bind click event for dynamic element goo.gl/zlEbnv
– Satinder singh
Aug 17 '15 at 5:14
comments disabled on deleted / locked posts / reviews |
I have a bit of code where I am looping through all the select boxes on a page and binding a .hover
event to them to do a bit of twiddling with their width on mouse on/off
.
This happens on page ready and works just fine.
The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.
I have found this plugin (jQuery Live Query Plugin), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.
javascript jquery events unobtrusive-javascript
I have a bit of code where I am looping through all the select boxes on a page and binding a .hover
event to them to do a bit of twiddling with their width on mouse on/off
.
This happens on page ready and works just fine.
The problem I have is that any select boxes I add via Ajax or DOM after the initial loop won't have the event bound.
I have found this plugin (jQuery Live Query Plugin), but before I add another 5k to my pages with a plugin, I want to see if anyone knows a way to do this, either with jQuery directly or by another option.
javascript jquery events unobtrusive-javascript
javascript jquery events unobtrusive-javascript
edited Dec 2 '16 at 10:27
Vikrant
3,876123755
3,876123755
asked Oct 14 '08 at 23:25
Eli
58.1k196980
58.1k196980
locked by Yvette Colomb♦ Jun 22 at 16:24
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
locked by Yvette Colomb♦ Jun 22 at 16:24
This question's answers are a collaborative effort: if you see something that can be improved, just edit the answer to improve it! No additional answers can be added here
11
Here's a detailed article on how to bind click event for dynamic element goo.gl/zlEbnv
– Satinder singh
Aug 17 '15 at 5:14
comments disabled on deleted / locked posts / reviews |
11
Here's a detailed article on how to bind click event for dynamic element goo.gl/zlEbnv
– Satinder singh
Aug 17 '15 at 5:14
11
11
Here's a detailed article on how to bind click event for dynamic element goo.gl/zlEbnv
– Satinder singh
Aug 17 '15 at 5:14
Here's a detailed article on how to bind click event for dynamic element goo.gl/zlEbnv
– Satinder singh
Aug 17 '15 at 5:14
comments disabled on deleted / locked posts / reviews |
23 Answers
23
active
oldest
votes
As of jQuery 1.7 you should use jQuery.fn.on
:
$(staticAncestors).on(eventName, dynamicChild, function() {});
Prior to this, the recommended approach was to use live()
:
$(selector).live( eventName, function(){} );
However, live()
was deprecated in 1.7 in favour of on()
, and completely removed in 1.9. The live()
signature:
$(selector).live( eventName, function(){} );
... can be replaced with the following on()
signature:
$(document).on( eventName, selector, function(){} );
For example, if your page was dynamically creating elements with the class name dosomething
you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document
. Though bear in mind document
may not be the most efficient option.
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
Any parent that exists at the time the event is bound is fine. For example
$('.buttons').on('click', 'button', function(){
// do something here
});
would apply to
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
5
Note that the live method only works for certain events, and not others such as loadedmetadata. (See the caveats section in the documentation.)
– Sam Dutton
Feb 17 '11 at 11:47
37
Learn more about event delegation here: learn.jquery.com/events/event-delegation.
– Felix Kling
Jun 7 '13 at 11:21
7
Any way to accomplish this with pure javascript/vanilla js?
– Ram Patra
Nov 12 '14 at 12:33
14
@Ramswaroop anything you can do in jQuery can be accomplished without jQuery. Here's a good example of event delegation without jQuery
– dave
Dec 8 '14 at 17:46
5
@dave I wonder why the answer you pointed out isn't listed here. Eli has clearly asked for a solution without any plugin if possible.
– Ram Patra
Dec 9 '14 at 7:14
|
show 7 more comments
There is a good explanation in the documentation of jQuery.fn.on
.
In short:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
.
Thus in the following example #dataTable tbody tr
must exist before the code is generated.
$("#dataTable tbody tr").on("click", function(event){
console.log($(this).text());
});
If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it:
$("#dataTable tbody").on("click", "tr", function(event){
console.log($(this).text());
});
In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody
, the first code example attaches a handler to 1,000 elements.
A delegated-events approach (the second code example) attaches an event handler to only one element, the tbody
, and the event only needs to bubble up one level (from the clicked tr
to tbody
).
Note: Delegated events do not work for SVG.
10
this'd be a better accepted answer because it'd be faster to delegate from the specific table rather than all the way from the document (the search area would be much smaller)
– msanjay
May 9 '14 at 18:14
5
@msanjay: Although targetting the search closer to the elements is preferred, the search/speed difference is very minor in practice. You would have to click 50,000 times a second to notice anything :)
– Gone Coding
Nov 12 '14 at 12:06
2
Can this approach be applied to handling checkbox clicks in a row by changingtr
to an appropriate selector, like'input[type=checkbox]'
, and this would be automatically handled for newly inserted rows?
– JoeBrockhaus
Nov 25 '14 at 17:26
add a comment |
This is a pure JavaScript solution without any libraries or plugins:
document.addEventListener('click', function (e) {
if (hasClass(e.target, 'bu')) {
// .bu clicked
// Do your thing
} else if (hasClass(e.target, 'test')) {
// .test clicked
// Do your other thing
}
}, false);
where hasClass
is
function hasClass(elem, className) {
return elem.className.split(' ').indexOf(className) > -1;
}
Live demo
Credit goes to Dave and Sime Vidas
Using more modern JS, hasClass
can be implemented as:
function hasClass(elem, className) {
return elem.classList.contains(className);
}
4
stackoverflow.com/questions/9106329/…
– zloctb
Jan 6 '16 at 14:57
6
You may use Element.classList instead of splitting
– Eugen Konkov
Aug 9 '16 at 10:07
2
@EugenKonkovElement.classList
is not supported supported on older browsers. For example, IE < 9.
– Ram Patra
Aug 9 '16 at 10:59
2
A nice article on how to get things done using vanilla script instead of jQuery - toddmotto.com/…
– Ram Patra
Jun 29 '17 at 9:25
1
how about bubbling? What if the click event happened on a child of the element you are interested in?
– Andreas Trantidis
Jul 6 '17 at 13:06
|
show 1 more comment
You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.
var mouseOverHandler = function() {
// Do stuff
};
var mouseOutHandler = function () {
// Do stuff
};
$(function() {
// On the document load, apply to existing elements
$('select').hover(mouseOverHandler, mouseOutHandler);
});
// This next part would be in the callback from your Ajax call
$("<select></select>")
.append( /* Your <option>s */ )
.hover(mouseOverHandler, mouseOutHandler)
.appendTo( /* Wherever you need the select box */ )
;
add a comment |
You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:
function addCallbacks(eles){
eles.hover(function(){alert("gotcha!")});
}
$(document).ready(function(){
addCallbacks($(".myEles"))
});
// ... add elements ...
addCallbacks($(".myNewElements"))
2
This post really helped me get a grasp on a problem I was having loading the same form and getting 1,2,4,8,16... submissions. Instead of using .live() I just used .bind() in my .load() callback. Problem solved. Thanks!
– Thomas McCabe
Aug 24 '11 at 9:24
add a comment |
Try to use .live()
instead of .bind()
; the .live()
will bind .hover
to your checkbox after the Ajax request executes.
30
The methodlive()
was deprecated in version 1.7 in favor ofon
and deleted in version 1.9.
– chridam
Jun 17 '14 at 12:30
add a comment |
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>
<input type="button" id="theButton" value="Click" />
<script type="text/javascript">
$(document).ready(function()
{
$('.FOO').live("click", function (){alert("It Works!")});
var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
autoOpen: false,
tite: 'Basic Dialog'
});
$('#theButton').click(function()
{
$dialog.dialog('open');
return('false');
});
$('#CUSTOM').click(function(){
//$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
var button = document.createElement("input");
button.setAttribute('class','FOO');
button.setAttribute('type','button');
button.setAttribute('value','CLICKMEE');
$('#container').append(button);
});
/* $('#FOO').click(function(){
alert("It Works!");
}); */
});
</script>
</body>
</html>
3
live is deprecated
– gorgi93
Jun 13 '13 at 9:55
add a comment |
Event binding on dynamically created elements
Single element:
$(document.body).on('click','.element', function(e) { });
Child Element:
$(document.body).on('click','.element *', function(e) { });
Notice the added *
. An event will be triggered for all children of that element.
I have noticed that:
$(document.body).on('click','.#element_id > element', function(e) { });
It is not working any more, but it was working before. I have been using jQuery from Google CDN, but I don't know if they changed it.
Yeap and they are not saying (document.body) its says ancestor wich could be pretty much anything
– MadeInDreams
Jan 23 '16 at 16:29
add a comment |
Another solution is to add the listener when creating the element. Instead of put the listener in the body, you put the listener in the element in the moment that you create it:
var myElement = $('<button/>', {
text: 'Go to Google!'
});
myElement.bind( 'click', goToGoogle);
myElement.append('body');
function goToGoogle(event){
window.location.replace("http://www.google.com");
}
Your code contains 1 mistake:myElement.append('body');
must bemyElement.appendTo('body');
. On the other hand, if there is no need for the further use of variablemyElement
it's easier and shorter this way:$('body').append($('<button/>', { text: 'Go to Google!' }).bind( 'click', goToGoogle));
– ddlab
May 11 '17 at 19:58
add a comment |
I prefer using the selector and I apply it on the document.
This binds itself on the document and will be applicable to the elements that will be rendered after page load.
For example:
$(document).on("click", $(selector), function() {
// Your code here
});
2
the selector shouldn't be enclosed by $, thus the correct format will be $(document).on( "click" , "selector" , function() { // Your code here });
– autopilot
Apr 9 at 4:21
It's also pointless to wrap a jQuery object around theselector
variable, when it must either contain a string or Element object which you can just pass directly to that argument ofon()
– Rory McCrossan
Jun 20 at 14:57
add a comment |
Take note of "MAIN" class the element is placed, for example,
<div class="container">
<ul class="select">
<li> First</li>
<li>Second</li>
</ul>
</div>
In the above scenario, the MAIN object the jQuery will watch is "container".
Then you will basically have elements names under container such as ul
, li
, and select
:
$(document).ready(function(e) {
$('.container').on( 'click',".select", function(e) {
alert("CLICKED");
});
});
add a comment |
You can attach event to element when dynamically created using jQuery(html, attributes)
.
As of jQuery 1.8, any jQuery instance method (a method of
jQuery.fn
) can be used as a property of the object passed to the
second parameter:
function handleDynamicElementEvent(event) {
console.log(event.type, this.value)
}
// create and attach event to dynamic element
jQuery("<select>", {
html: $.map(Array(3), function(_, index) {
return new Option(index, index)
}),
on: {
change: handleDynamicElementEvent
}
})
.appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
add a comment |
you could use
$('.buttons').on('click', 'button', function(){
// your magic goes here
});
or
$('.buttons').delegate('button', 'click', function() {
// your magic goes here
});
these two methods are equivalent but have a different order of parameters.
see: jQuery Delegate Event
delegate()
is now deprecated. Do not use it.
– Rory McCrossan
Jun 20 at 14:58
add a comment |
Any parent that exists at the time the event is bound and if your page was dynamically creating elements with the class name button you would bind the event to a parent which already exists
$(document).ready(function(){
//Particular Parent chield click
$(".buttons").on("click","button",function(){
alert("Clicked");
});
//Dynamic event bind on button class
$(document).on("click",".button",function(){
alert("Dymamic Clicked");
});
$("input").addClass("button");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
<input type="button" value="1">
<button>2</button>
<input type="text">
<button>3</button>
<input type="button" value="5">
</div>
<button>6</button>
add a comment |
Here is why dynamically created elements do not respond to clicks :
var body = $("body");
var btns = $("button");
var btnB = $("<button>B</button>");
// `<button>B</button>` is not yet in the document.
// Thus, `$("button")` gives `[<button>A</button>]`.
// Only `<button>A</button>` gets a click listener.
btns.on("click", function () {
console.log(this);
});
// Too late for `<button>B</button>`...
body.append(btnB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
As a workaround, you have to listen to all clicks and check the source element :
var body = $("body");
var btnB = $("<button>B</button>");
var btnC = $("<button>C</button>");
// Listen to all clicks and
// check if the source element
// is a `<button></button>`.
body.on("click", function (ev) {
if ($(ev.target).is("button")) {
console.log(ev.target);
}
});
// Now you can add any number
// of `<button></button>`.
body.append(btnB);
body.append(btnC);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
This is called "Event Delegation". Good news, it's a builtin feature in jQuery :-)
var i = 11;
var body = $("body");
body.on("click", "button", function () {
var letter = (i++).toString(36).toUpperCase();
body.append($("<button>" + letter + "</button>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
add a comment |
Try like this -
$(document).on( 'click', '.click-activity', function () { ... });
add a comment |
Use the .on()
method of jQuery http://api.jquery.com/on/ to attach event handlers to live element.
Also as of version 1.9 .live()
method is removed.
add a comment |
Bind the event to a parent which already exists:
$(document).on("click", "selector", function() {
// Your code here
});
add a comment |
More flexible solution to create elements and bind events (source)
// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});
//creating a dynamic button
var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });
// binding the event
$btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
console.log('clicked');
});
// append dynamic button to the dynamic container
$div.append($btn);
// add the dynamically created element(s) to a static element
$("#box").append($div);
Note: This will create an event handler instance for each element (may affect performance when used in loops)
add a comment |
I prefer to have event listeners deployed in a modular function fashion rather than scripting a document
level event listener. So, I do like below. Note, you can't oversubscribe an element with the same event listener so don't worry about attaching a listener more than once - only one sticks.
var iterations = 4;
var button;
var body = document.querySelector("body");
for (var i = 0; i < iterations; i++) {
button = document.createElement("button");
button.classList.add("my-button");
button.appendChild(document.createTextNode(i));
button.addEventListener("click", myButtonWasClicked);
body.appendChild(button);
}
function myButtonWasClicked(e) {
console.log(e.target); //access to this specific button
}
I prefer this implementation; I just have to set up a call back
– William
Oct 22 at 10:18
add a comment |
This is done by event delegation. Event will bind on wrapper-class element but will be delegated to selector-class element. This is how it works.
$('.wrapper-class').on("click", '.selector-class', function() {
// Your code here
});
Note:
wrapper-class element can be anything ex. document, body or your wrapper. Wrapper should already exist.
add a comment |
<html>
<head>
<title>HTML Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="hover-id">
Hello World
</div>
<script>
jQuery(document).ready(function($){
$(document).on('mouseover', '#hover-id', function(){
$(this).css('color','yellowgreen');
});
$(document).on('mouseout', '#hover-id', function(){
$(this).css('color','black');
});
});
</script>
</body>
</html>
1
While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
– Palec
Sep 30 '17 at 11:07
add a comment |
I was looking a solution to get $.bind
and $.unbind
working without problems in dynamically added elements.
As on() makes the trick to attach events, in order to create a fake unbind on those I came to:
const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );
// unbind the click
$('body').on('click', 'button.send', function(){} );
The unbinding does not work, this simply adds another event which points to an empty function...
– Fabian Bigler
Nov 9 at 11:28
add a comment |
protected by lifetimes Mar 24 '14 at 10:09
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
23 Answers
23
active
oldest
votes
23 Answers
23
active
oldest
votes
active
oldest
votes
active
oldest
votes
As of jQuery 1.7 you should use jQuery.fn.on
:
$(staticAncestors).on(eventName, dynamicChild, function() {});
Prior to this, the recommended approach was to use live()
:
$(selector).live( eventName, function(){} );
However, live()
was deprecated in 1.7 in favour of on()
, and completely removed in 1.9. The live()
signature:
$(selector).live( eventName, function(){} );
... can be replaced with the following on()
signature:
$(document).on( eventName, selector, function(){} );
For example, if your page was dynamically creating elements with the class name dosomething
you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document
. Though bear in mind document
may not be the most efficient option.
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
Any parent that exists at the time the event is bound is fine. For example
$('.buttons').on('click', 'button', function(){
// do something here
});
would apply to
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
5
Note that the live method only works for certain events, and not others such as loadedmetadata. (See the caveats section in the documentation.)
– Sam Dutton
Feb 17 '11 at 11:47
37
Learn more about event delegation here: learn.jquery.com/events/event-delegation.
– Felix Kling
Jun 7 '13 at 11:21
7
Any way to accomplish this with pure javascript/vanilla js?
– Ram Patra
Nov 12 '14 at 12:33
14
@Ramswaroop anything you can do in jQuery can be accomplished without jQuery. Here's a good example of event delegation without jQuery
– dave
Dec 8 '14 at 17:46
5
@dave I wonder why the answer you pointed out isn't listed here. Eli has clearly asked for a solution without any plugin if possible.
– Ram Patra
Dec 9 '14 at 7:14
|
show 7 more comments
As of jQuery 1.7 you should use jQuery.fn.on
:
$(staticAncestors).on(eventName, dynamicChild, function() {});
Prior to this, the recommended approach was to use live()
:
$(selector).live( eventName, function(){} );
However, live()
was deprecated in 1.7 in favour of on()
, and completely removed in 1.9. The live()
signature:
$(selector).live( eventName, function(){} );
... can be replaced with the following on()
signature:
$(document).on( eventName, selector, function(){} );
For example, if your page was dynamically creating elements with the class name dosomething
you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document
. Though bear in mind document
may not be the most efficient option.
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
Any parent that exists at the time the event is bound is fine. For example
$('.buttons').on('click', 'button', function(){
// do something here
});
would apply to
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
5
Note that the live method only works for certain events, and not others such as loadedmetadata. (See the caveats section in the documentation.)
– Sam Dutton
Feb 17 '11 at 11:47
37
Learn more about event delegation here: learn.jquery.com/events/event-delegation.
– Felix Kling
Jun 7 '13 at 11:21
7
Any way to accomplish this with pure javascript/vanilla js?
– Ram Patra
Nov 12 '14 at 12:33
14
@Ramswaroop anything you can do in jQuery can be accomplished without jQuery. Here's a good example of event delegation without jQuery
– dave
Dec 8 '14 at 17:46
5
@dave I wonder why the answer you pointed out isn't listed here. Eli has clearly asked for a solution without any plugin if possible.
– Ram Patra
Dec 9 '14 at 7:14
|
show 7 more comments
As of jQuery 1.7 you should use jQuery.fn.on
:
$(staticAncestors).on(eventName, dynamicChild, function() {});
Prior to this, the recommended approach was to use live()
:
$(selector).live( eventName, function(){} );
However, live()
was deprecated in 1.7 in favour of on()
, and completely removed in 1.9. The live()
signature:
$(selector).live( eventName, function(){} );
... can be replaced with the following on()
signature:
$(document).on( eventName, selector, function(){} );
For example, if your page was dynamically creating elements with the class name dosomething
you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document
. Though bear in mind document
may not be the most efficient option.
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
Any parent that exists at the time the event is bound is fine. For example
$('.buttons').on('click', 'button', function(){
// do something here
});
would apply to
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
As of jQuery 1.7 you should use jQuery.fn.on
:
$(staticAncestors).on(eventName, dynamicChild, function() {});
Prior to this, the recommended approach was to use live()
:
$(selector).live( eventName, function(){} );
However, live()
was deprecated in 1.7 in favour of on()
, and completely removed in 1.9. The live()
signature:
$(selector).live( eventName, function(){} );
... can be replaced with the following on()
signature:
$(document).on( eventName, selector, function(){} );
For example, if your page was dynamically creating elements with the class name dosomething
you would bind the event to a parent which already exists (this is the nub of the problem here, you need something that exists to bind to, don't bind to the dynamic content), this can be (and the easiest option) is document
. Though bear in mind document
may not be the most efficient option.
$(document).on('mouseover mouseout', '.dosomething', function(){
// what you want to happen when mouseover and mouseout
// occurs on elements that match '.dosomething'
});
Any parent that exists at the time the event is bound is fine. For example
$('.buttons').on('click', 'button', function(){
// do something here
});
would apply to
<div class="buttons">
<!-- <button>s that are generated dynamically and added here -->
</div>
edited Mar 12 at 14:43
community wiki
14 revs, 13 users 28%
Popnoodles
5
Note that the live method only works for certain events, and not others such as loadedmetadata. (See the caveats section in the documentation.)
– Sam Dutton
Feb 17 '11 at 11:47
37
Learn more about event delegation here: learn.jquery.com/events/event-delegation.
– Felix Kling
Jun 7 '13 at 11:21
7
Any way to accomplish this with pure javascript/vanilla js?
– Ram Patra
Nov 12 '14 at 12:33
14
@Ramswaroop anything you can do in jQuery can be accomplished without jQuery. Here's a good example of event delegation without jQuery
– dave
Dec 8 '14 at 17:46
5
@dave I wonder why the answer you pointed out isn't listed here. Eli has clearly asked for a solution without any plugin if possible.
– Ram Patra
Dec 9 '14 at 7:14
|
show 7 more comments
5
Note that the live method only works for certain events, and not others such as loadedmetadata. (See the caveats section in the documentation.)
– Sam Dutton
Feb 17 '11 at 11:47
37
Learn more about event delegation here: learn.jquery.com/events/event-delegation.
– Felix Kling
Jun 7 '13 at 11:21
7
Any way to accomplish this with pure javascript/vanilla js?
– Ram Patra
Nov 12 '14 at 12:33
14
@Ramswaroop anything you can do in jQuery can be accomplished without jQuery. Here's a good example of event delegation without jQuery
– dave
Dec 8 '14 at 17:46
5
@dave I wonder why the answer you pointed out isn't listed here. Eli has clearly asked for a solution without any plugin if possible.
– Ram Patra
Dec 9 '14 at 7:14
5
5
Note that the live method only works for certain events, and not others such as loadedmetadata. (See the caveats section in the documentation.)
– Sam Dutton
Feb 17 '11 at 11:47
Note that the live method only works for certain events, and not others such as loadedmetadata. (See the caveats section in the documentation.)
– Sam Dutton
Feb 17 '11 at 11:47
37
37
Learn more about event delegation here: learn.jquery.com/events/event-delegation.
– Felix Kling
Jun 7 '13 at 11:21
Learn more about event delegation here: learn.jquery.com/events/event-delegation.
– Felix Kling
Jun 7 '13 at 11:21
7
7
Any way to accomplish this with pure javascript/vanilla js?
– Ram Patra
Nov 12 '14 at 12:33
Any way to accomplish this with pure javascript/vanilla js?
– Ram Patra
Nov 12 '14 at 12:33
14
14
@Ramswaroop anything you can do in jQuery can be accomplished without jQuery. Here's a good example of event delegation without jQuery
– dave
Dec 8 '14 at 17:46
@Ramswaroop anything you can do in jQuery can be accomplished without jQuery. Here's a good example of event delegation without jQuery
– dave
Dec 8 '14 at 17:46
5
5
@dave I wonder why the answer you pointed out isn't listed here. Eli has clearly asked for a solution without any plugin if possible.
– Ram Patra
Dec 9 '14 at 7:14
@dave I wonder why the answer you pointed out isn't listed here. Eli has clearly asked for a solution without any plugin if possible.
– Ram Patra
Dec 9 '14 at 7:14
|
show 7 more comments
There is a good explanation in the documentation of jQuery.fn.on
.
In short:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
.
Thus in the following example #dataTable tbody tr
must exist before the code is generated.
$("#dataTable tbody tr").on("click", function(event){
console.log($(this).text());
});
If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it:
$("#dataTable tbody").on("click", "tr", function(event){
console.log($(this).text());
});
In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody
, the first code example attaches a handler to 1,000 elements.
A delegated-events approach (the second code example) attaches an event handler to only one element, the tbody
, and the event only needs to bubble up one level (from the clicked tr
to tbody
).
Note: Delegated events do not work for SVG.
10
this'd be a better accepted answer because it'd be faster to delegate from the specific table rather than all the way from the document (the search area would be much smaller)
– msanjay
May 9 '14 at 18:14
5
@msanjay: Although targetting the search closer to the elements is preferred, the search/speed difference is very minor in practice. You would have to click 50,000 times a second to notice anything :)
– Gone Coding
Nov 12 '14 at 12:06
2
Can this approach be applied to handling checkbox clicks in a row by changingtr
to an appropriate selector, like'input[type=checkbox]'
, and this would be automatically handled for newly inserted rows?
– JoeBrockhaus
Nov 25 '14 at 17:26
add a comment |
There is a good explanation in the documentation of jQuery.fn.on
.
In short:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
.
Thus in the following example #dataTable tbody tr
must exist before the code is generated.
$("#dataTable tbody tr").on("click", function(event){
console.log($(this).text());
});
If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it:
$("#dataTable tbody").on("click", "tr", function(event){
console.log($(this).text());
});
In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody
, the first code example attaches a handler to 1,000 elements.
A delegated-events approach (the second code example) attaches an event handler to only one element, the tbody
, and the event only needs to bubble up one level (from the clicked tr
to tbody
).
Note: Delegated events do not work for SVG.
10
this'd be a better accepted answer because it'd be faster to delegate from the specific table rather than all the way from the document (the search area would be much smaller)
– msanjay
May 9 '14 at 18:14
5
@msanjay: Although targetting the search closer to the elements is preferred, the search/speed difference is very minor in practice. You would have to click 50,000 times a second to notice anything :)
– Gone Coding
Nov 12 '14 at 12:06
2
Can this approach be applied to handling checkbox clicks in a row by changingtr
to an appropriate selector, like'input[type=checkbox]'
, and this would be automatically handled for newly inserted rows?
– JoeBrockhaus
Nov 25 '14 at 17:26
add a comment |
There is a good explanation in the documentation of jQuery.fn.on
.
In short:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
.
Thus in the following example #dataTable tbody tr
must exist before the code is generated.
$("#dataTable tbody tr").on("click", function(event){
console.log($(this).text());
});
If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it:
$("#dataTable tbody").on("click", "tr", function(event){
console.log($(this).text());
});
In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody
, the first code example attaches a handler to 1,000 elements.
A delegated-events approach (the second code example) attaches an event handler to only one element, the tbody
, and the event only needs to bubble up one level (from the clicked tr
to tbody
).
Note: Delegated events do not work for SVG.
There is a good explanation in the documentation of jQuery.fn.on
.
In short:
Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to
.on()
.
Thus in the following example #dataTable tbody tr
must exist before the code is generated.
$("#dataTable tbody tr").on("click", function(event){
console.log($(this).text());
});
If new HTML is being injected into the page, it is preferable to use delegated events to attach an event handler, as described next.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time. For example, if the table exists, but the rows are added dynamically using code, the following will handle it:
$("#dataTable tbody").on("click", "tr", function(event){
console.log($(this).text());
});
In addition to their ability to handle events on descendant elements which are not yet created, another advantage of delegated events is their potential for much lower overhead when many elements must be monitored. On a data table with 1,000 rows in its tbody
, the first code example attaches a handler to 1,000 elements.
A delegated-events approach (the second code example) attaches an event handler to only one element, the tbody
, and the event only needs to bubble up one level (from the clicked tr
to tbody
).
Note: Delegated events do not work for SVG.
edited Apr 30 '17 at 21:34
user664833
10.7k1766111
10.7k1766111
answered Aug 9 '13 at 9:51
Ronen Rabinovici
4,51021831
4,51021831
10
this'd be a better accepted answer because it'd be faster to delegate from the specific table rather than all the way from the document (the search area would be much smaller)
– msanjay
May 9 '14 at 18:14
5
@msanjay: Although targetting the search closer to the elements is preferred, the search/speed difference is very minor in practice. You would have to click 50,000 times a second to notice anything :)
– Gone Coding
Nov 12 '14 at 12:06
2
Can this approach be applied to handling checkbox clicks in a row by changingtr
to an appropriate selector, like'input[type=checkbox]'
, and this would be automatically handled for newly inserted rows?
– JoeBrockhaus
Nov 25 '14 at 17:26
add a comment |
10
this'd be a better accepted answer because it'd be faster to delegate from the specific table rather than all the way from the document (the search area would be much smaller)
– msanjay
May 9 '14 at 18:14
5
@msanjay: Although targetting the search closer to the elements is preferred, the search/speed difference is very minor in practice. You would have to click 50,000 times a second to notice anything :)
– Gone Coding
Nov 12 '14 at 12:06
2
Can this approach be applied to handling checkbox clicks in a row by changingtr
to an appropriate selector, like'input[type=checkbox]'
, and this would be automatically handled for newly inserted rows?
– JoeBrockhaus
Nov 25 '14 at 17:26
10
10
this'd be a better accepted answer because it'd be faster to delegate from the specific table rather than all the way from the document (the search area would be much smaller)
– msanjay
May 9 '14 at 18:14
this'd be a better accepted answer because it'd be faster to delegate from the specific table rather than all the way from the document (the search area would be much smaller)
– msanjay
May 9 '14 at 18:14
5
5
@msanjay: Although targetting the search closer to the elements is preferred, the search/speed difference is very minor in practice. You would have to click 50,000 times a second to notice anything :)
– Gone Coding
Nov 12 '14 at 12:06
@msanjay: Although targetting the search closer to the elements is preferred, the search/speed difference is very minor in practice. You would have to click 50,000 times a second to notice anything :)
– Gone Coding
Nov 12 '14 at 12:06
2
2
Can this approach be applied to handling checkbox clicks in a row by changing
tr
to an appropriate selector, like 'input[type=checkbox]'
, and this would be automatically handled for newly inserted rows?– JoeBrockhaus
Nov 25 '14 at 17:26
Can this approach be applied to handling checkbox clicks in a row by changing
tr
to an appropriate selector, like 'input[type=checkbox]'
, and this would be automatically handled for newly inserted rows?– JoeBrockhaus
Nov 25 '14 at 17:26
add a comment |
This is a pure JavaScript solution without any libraries or plugins:
document.addEventListener('click', function (e) {
if (hasClass(e.target, 'bu')) {
// .bu clicked
// Do your thing
} else if (hasClass(e.target, 'test')) {
// .test clicked
// Do your other thing
}
}, false);
where hasClass
is
function hasClass(elem, className) {
return elem.className.split(' ').indexOf(className) > -1;
}
Live demo
Credit goes to Dave and Sime Vidas
Using more modern JS, hasClass
can be implemented as:
function hasClass(elem, className) {
return elem.classList.contains(className);
}
4
stackoverflow.com/questions/9106329/…
– zloctb
Jan 6 '16 at 14:57
6
You may use Element.classList instead of splitting
– Eugen Konkov
Aug 9 '16 at 10:07
2
@EugenKonkovElement.classList
is not supported supported on older browsers. For example, IE < 9.
– Ram Patra
Aug 9 '16 at 10:59
2
A nice article on how to get things done using vanilla script instead of jQuery - toddmotto.com/…
– Ram Patra
Jun 29 '17 at 9:25
1
how about bubbling? What if the click event happened on a child of the element you are interested in?
– Andreas Trantidis
Jul 6 '17 at 13:06
|
show 1 more comment
This is a pure JavaScript solution without any libraries or plugins:
document.addEventListener('click', function (e) {
if (hasClass(e.target, 'bu')) {
// .bu clicked
// Do your thing
} else if (hasClass(e.target, 'test')) {
// .test clicked
// Do your other thing
}
}, false);
where hasClass
is
function hasClass(elem, className) {
return elem.className.split(' ').indexOf(className) > -1;
}
Live demo
Credit goes to Dave and Sime Vidas
Using more modern JS, hasClass
can be implemented as:
function hasClass(elem, className) {
return elem.classList.contains(className);
}
4
stackoverflow.com/questions/9106329/…
– zloctb
Jan 6 '16 at 14:57
6
You may use Element.classList instead of splitting
– Eugen Konkov
Aug 9 '16 at 10:07
2
@EugenKonkovElement.classList
is not supported supported on older browsers. For example, IE < 9.
– Ram Patra
Aug 9 '16 at 10:59
2
A nice article on how to get things done using vanilla script instead of jQuery - toddmotto.com/…
– Ram Patra
Jun 29 '17 at 9:25
1
how about bubbling? What if the click event happened on a child of the element you are interested in?
– Andreas Trantidis
Jul 6 '17 at 13:06
|
show 1 more comment
This is a pure JavaScript solution without any libraries or plugins:
document.addEventListener('click', function (e) {
if (hasClass(e.target, 'bu')) {
// .bu clicked
// Do your thing
} else if (hasClass(e.target, 'test')) {
// .test clicked
// Do your other thing
}
}, false);
where hasClass
is
function hasClass(elem, className) {
return elem.className.split(' ').indexOf(className) > -1;
}
Live demo
Credit goes to Dave and Sime Vidas
Using more modern JS, hasClass
can be implemented as:
function hasClass(elem, className) {
return elem.classList.contains(className);
}
This is a pure JavaScript solution without any libraries or plugins:
document.addEventListener('click', function (e) {
if (hasClass(e.target, 'bu')) {
// .bu clicked
// Do your thing
} else if (hasClass(e.target, 'test')) {
// .test clicked
// Do your other thing
}
}, false);
where hasClass
is
function hasClass(elem, className) {
return elem.className.split(' ').indexOf(className) > -1;
}
Live demo
Credit goes to Dave and Sime Vidas
Using more modern JS, hasClass
can be implemented as:
function hasClass(elem, className) {
return elem.classList.contains(className);
}
edited Feb 27 at 20:25
Barmar
419k34243344
419k34243344
answered Dec 9 '14 at 7:59
Ram Patra
9,874104459
9,874104459
4
stackoverflow.com/questions/9106329/…
– zloctb
Jan 6 '16 at 14:57
6
You may use Element.classList instead of splitting
– Eugen Konkov
Aug 9 '16 at 10:07
2
@EugenKonkovElement.classList
is not supported supported on older browsers. For example, IE < 9.
– Ram Patra
Aug 9 '16 at 10:59
2
A nice article on how to get things done using vanilla script instead of jQuery - toddmotto.com/…
– Ram Patra
Jun 29 '17 at 9:25
1
how about bubbling? What if the click event happened on a child of the element you are interested in?
– Andreas Trantidis
Jul 6 '17 at 13:06
|
show 1 more comment
4
stackoverflow.com/questions/9106329/…
– zloctb
Jan 6 '16 at 14:57
6
You may use Element.classList instead of splitting
– Eugen Konkov
Aug 9 '16 at 10:07
2
@EugenKonkovElement.classList
is not supported supported on older browsers. For example, IE < 9.
– Ram Patra
Aug 9 '16 at 10:59
2
A nice article on how to get things done using vanilla script instead of jQuery - toddmotto.com/…
– Ram Patra
Jun 29 '17 at 9:25
1
how about bubbling? What if the click event happened on a child of the element you are interested in?
– Andreas Trantidis
Jul 6 '17 at 13:06
4
4
stackoverflow.com/questions/9106329/…
– zloctb
Jan 6 '16 at 14:57
stackoverflow.com/questions/9106329/…
– zloctb
Jan 6 '16 at 14:57
6
6
You may use Element.classList instead of splitting
– Eugen Konkov
Aug 9 '16 at 10:07
You may use Element.classList instead of splitting
– Eugen Konkov
Aug 9 '16 at 10:07
2
2
@EugenKonkov
Element.classList
is not supported supported on older browsers. For example, IE < 9.– Ram Patra
Aug 9 '16 at 10:59
@EugenKonkov
Element.classList
is not supported supported on older browsers. For example, IE < 9.– Ram Patra
Aug 9 '16 at 10:59
2
2
A nice article on how to get things done using vanilla script instead of jQuery - toddmotto.com/…
– Ram Patra
Jun 29 '17 at 9:25
A nice article on how to get things done using vanilla script instead of jQuery - toddmotto.com/…
– Ram Patra
Jun 29 '17 at 9:25
1
1
how about bubbling? What if the click event happened on a child of the element you are interested in?
– Andreas Trantidis
Jul 6 '17 at 13:06
how about bubbling? What if the click event happened on a child of the element you are interested in?
– Andreas Trantidis
Jul 6 '17 at 13:06
|
show 1 more comment
You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.
var mouseOverHandler = function() {
// Do stuff
};
var mouseOutHandler = function () {
// Do stuff
};
$(function() {
// On the document load, apply to existing elements
$('select').hover(mouseOverHandler, mouseOutHandler);
});
// This next part would be in the callback from your Ajax call
$("<select></select>")
.append( /* Your <option>s */ )
.hover(mouseOverHandler, mouseOutHandler)
.appendTo( /* Wherever you need the select box */ )
;
add a comment |
You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.
var mouseOverHandler = function() {
// Do stuff
};
var mouseOutHandler = function () {
// Do stuff
};
$(function() {
// On the document load, apply to existing elements
$('select').hover(mouseOverHandler, mouseOutHandler);
});
// This next part would be in the callback from your Ajax call
$("<select></select>")
.append( /* Your <option>s */ )
.hover(mouseOverHandler, mouseOutHandler)
.appendTo( /* Wherever you need the select box */ )
;
add a comment |
You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.
var mouseOverHandler = function() {
// Do stuff
};
var mouseOutHandler = function () {
// Do stuff
};
$(function() {
// On the document load, apply to existing elements
$('select').hover(mouseOverHandler, mouseOutHandler);
});
// This next part would be in the callback from your Ajax call
$("<select></select>")
.append( /* Your <option>s */ )
.hover(mouseOverHandler, mouseOutHandler)
.appendTo( /* Wherever you need the select box */ )
;
You can add events to objects when you create them. If you are adding the same events to multiple objects at different times, creating a named function might be the way to go.
var mouseOverHandler = function() {
// Do stuff
};
var mouseOutHandler = function () {
// Do stuff
};
$(function() {
// On the document load, apply to existing elements
$('select').hover(mouseOverHandler, mouseOutHandler);
});
// This next part would be in the callback from your Ajax call
$("<select></select>")
.append( /* Your <option>s */ )
.hover(mouseOverHandler, mouseOutHandler)
.appendTo( /* Wherever you need the select box */ )
;
edited Apr 22 '16 at 21:41
Peter Mortensen
13.5k1983111
13.5k1983111
answered Oct 14 '08 at 23:31
nickf
369k171581687
369k171581687
add a comment |
add a comment |
You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:
function addCallbacks(eles){
eles.hover(function(){alert("gotcha!")});
}
$(document).ready(function(){
addCallbacks($(".myEles"))
});
// ... add elements ...
addCallbacks($(".myNewElements"))
2
This post really helped me get a grasp on a problem I was having loading the same form and getting 1,2,4,8,16... submissions. Instead of using .live() I just used .bind() in my .load() callback. Problem solved. Thanks!
– Thomas McCabe
Aug 24 '11 at 9:24
add a comment |
You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:
function addCallbacks(eles){
eles.hover(function(){alert("gotcha!")});
}
$(document).ready(function(){
addCallbacks($(".myEles"))
});
// ... add elements ...
addCallbacks($(".myNewElements"))
2
This post really helped me get a grasp on a problem I was having loading the same form and getting 1,2,4,8,16... submissions. Instead of using .live() I just used .bind() in my .load() callback. Problem solved. Thanks!
– Thomas McCabe
Aug 24 '11 at 9:24
add a comment |
You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:
function addCallbacks(eles){
eles.hover(function(){alert("gotcha!")});
}
$(document).ready(function(){
addCallbacks($(".myEles"))
});
// ... add elements ...
addCallbacks($(".myNewElements"))
You could simply wrap your event binding call up into a function and then invoke it twice: once on document ready and once after your event that adds the new DOM elements. If you do that you'll want to avoid binding the same event twice on the existing elements so you'll need either unbind the existing events or (better) only bind to the DOM elements that are newly created. The code would look something like this:
function addCallbacks(eles){
eles.hover(function(){alert("gotcha!")});
}
$(document).ready(function(){
addCallbacks($(".myEles"))
});
// ... add elements ...
addCallbacks($(".myNewElements"))
edited Apr 22 '16 at 21:41
Peter Mortensen
13.5k1983111
13.5k1983111
answered Oct 14 '08 at 23:35
Greg Borenstein
1,21621116
1,21621116
2
This post really helped me get a grasp on a problem I was having loading the same form and getting 1,2,4,8,16... submissions. Instead of using .live() I just used .bind() in my .load() callback. Problem solved. Thanks!
– Thomas McCabe
Aug 24 '11 at 9:24
add a comment |
2
This post really helped me get a grasp on a problem I was having loading the same form and getting 1,2,4,8,16... submissions. Instead of using .live() I just used .bind() in my .load() callback. Problem solved. Thanks!
– Thomas McCabe
Aug 24 '11 at 9:24
2
2
This post really helped me get a grasp on a problem I was having loading the same form and getting 1,2,4,8,16... submissions. Instead of using .live() I just used .bind() in my .load() callback. Problem solved. Thanks!
– Thomas McCabe
Aug 24 '11 at 9:24
This post really helped me get a grasp on a problem I was having loading the same form and getting 1,2,4,8,16... submissions. Instead of using .live() I just used .bind() in my .load() callback. Problem solved. Thanks!
– Thomas McCabe
Aug 24 '11 at 9:24
add a comment |
Try to use .live()
instead of .bind()
; the .live()
will bind .hover
to your checkbox after the Ajax request executes.
30
The methodlive()
was deprecated in version 1.7 in favor ofon
and deleted in version 1.9.
– chridam
Jun 17 '14 at 12:30
add a comment |
Try to use .live()
instead of .bind()
; the .live()
will bind .hover
to your checkbox after the Ajax request executes.
30
The methodlive()
was deprecated in version 1.7 in favor ofon
and deleted in version 1.9.
– chridam
Jun 17 '14 at 12:30
add a comment |
Try to use .live()
instead of .bind()
; the .live()
will bind .hover
to your checkbox after the Ajax request executes.
Try to use .live()
instead of .bind()
; the .live()
will bind .hover
to your checkbox after the Ajax request executes.
edited Sep 6 '15 at 20:50
Willi Mentzel
8,251114467
8,251114467
answered Mar 21 '11 at 22:35
user670265
39932
39932
30
The methodlive()
was deprecated in version 1.7 in favor ofon
and deleted in version 1.9.
– chridam
Jun 17 '14 at 12:30
add a comment |
30
The methodlive()
was deprecated in version 1.7 in favor ofon
and deleted in version 1.9.
– chridam
Jun 17 '14 at 12:30
30
30
The method
live()
was deprecated in version 1.7 in favor of on
and deleted in version 1.9.– chridam
Jun 17 '14 at 12:30
The method
live()
was deprecated in version 1.7 in favor of on
and deleted in version 1.9.– chridam
Jun 17 '14 at 12:30
add a comment |
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>
<input type="button" id="theButton" value="Click" />
<script type="text/javascript">
$(document).ready(function()
{
$('.FOO').live("click", function (){alert("It Works!")});
var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
autoOpen: false,
tite: 'Basic Dialog'
});
$('#theButton').click(function()
{
$dialog.dialog('open');
return('false');
});
$('#CUSTOM').click(function(){
//$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
var button = document.createElement("input");
button.setAttribute('class','FOO');
button.setAttribute('type','button');
button.setAttribute('value','CLICKMEE');
$('#container').append(button);
});
/* $('#FOO').click(function(){
alert("It Works!");
}); */
});
</script>
</body>
</html>
3
live is deprecated
– gorgi93
Jun 13 '13 at 9:55
add a comment |
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>
<input type="button" id="theButton" value="Click" />
<script type="text/javascript">
$(document).ready(function()
{
$('.FOO').live("click", function (){alert("It Works!")});
var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
autoOpen: false,
tite: 'Basic Dialog'
});
$('#theButton').click(function()
{
$dialog.dialog('open');
return('false');
});
$('#CUSTOM').click(function(){
//$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
var button = document.createElement("input");
button.setAttribute('class','FOO');
button.setAttribute('type','button');
button.setAttribute('value','CLICKMEE');
$('#container').append(button);
});
/* $('#FOO').click(function(){
alert("It Works!");
}); */
});
</script>
</body>
</html>
3
live is deprecated
– gorgi93
Jun 13 '13 at 9:55
add a comment |
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>
<input type="button" id="theButton" value="Click" />
<script type="text/javascript">
$(document).ready(function()
{
$('.FOO').live("click", function (){alert("It Works!")});
var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
autoOpen: false,
tite: 'Basic Dialog'
});
$('#theButton').click(function()
{
$dialog.dialog('open');
return('false');
});
$('#CUSTOM').click(function(){
//$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
var button = document.createElement("input");
button.setAttribute('class','FOO');
button.setAttribute('type','button');
button.setAttribute('value','CLICKMEE');
$('#container').append(button);
});
/* $('#FOO').click(function(){
alert("It Works!");
}); */
});
</script>
</body>
</html>
You can use the live() method to bind elements (even newly created ones) to events and handlers, like the onclick event.
Here is a sample code I have written, where you can see how the live() method binds chosen elements, even newly created ones, to events:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.16/jquery-ui.min.js"></script>
<input type="button" id="theButton" value="Click" />
<script type="text/javascript">
$(document).ready(function()
{
$('.FOO').live("click", function (){alert("It Works!")});
var $dialog = $('<div></div>').html('<div id="container"><input type ="button" id="CUSTOM" value="click"/>This dialog will show every time!</div>').dialog({
autoOpen: false,
tite: 'Basic Dialog'
});
$('#theButton').click(function()
{
$dialog.dialog('open');
return('false');
});
$('#CUSTOM').click(function(){
//$('#container').append('<input type="button" value="clickmee" class="FOO" /></br>');
var button = document.createElement("input");
button.setAttribute('class','FOO');
button.setAttribute('type','button');
button.setAttribute('value','CLICKMEE');
$('#container').append(button);
});
/* $('#FOO').click(function(){
alert("It Works!");
}); */
});
</script>
</body>
</html>
edited Apr 22 '16 at 21:44
Peter Mortensen
13.5k1983111
13.5k1983111
answered Dec 21 '11 at 7:26
Fazi
2,76422122
2,76422122
3
live is deprecated
– gorgi93
Jun 13 '13 at 9:55
add a comment |
3
live is deprecated
– gorgi93
Jun 13 '13 at 9:55
3
3
live is deprecated
– gorgi93
Jun 13 '13 at 9:55
live is deprecated
– gorgi93
Jun 13 '13 at 9:55
add a comment |
Event binding on dynamically created elements
Single element:
$(document.body).on('click','.element', function(e) { });
Child Element:
$(document.body).on('click','.element *', function(e) { });
Notice the added *
. An event will be triggered for all children of that element.
I have noticed that:
$(document.body).on('click','.#element_id > element', function(e) { });
It is not working any more, but it was working before. I have been using jQuery from Google CDN, but I don't know if they changed it.
Yeap and they are not saying (document.body) its says ancestor wich could be pretty much anything
– MadeInDreams
Jan 23 '16 at 16:29
add a comment |
Event binding on dynamically created elements
Single element:
$(document.body).on('click','.element', function(e) { });
Child Element:
$(document.body).on('click','.element *', function(e) { });
Notice the added *
. An event will be triggered for all children of that element.
I have noticed that:
$(document.body).on('click','.#element_id > element', function(e) { });
It is not working any more, but it was working before. I have been using jQuery from Google CDN, but I don't know if they changed it.
Yeap and they are not saying (document.body) its says ancestor wich could be pretty much anything
– MadeInDreams
Jan 23 '16 at 16:29
add a comment |
Event binding on dynamically created elements
Single element:
$(document.body).on('click','.element', function(e) { });
Child Element:
$(document.body).on('click','.element *', function(e) { });
Notice the added *
. An event will be triggered for all children of that element.
I have noticed that:
$(document.body).on('click','.#element_id > element', function(e) { });
It is not working any more, but it was working before. I have been using jQuery from Google CDN, but I don't know if they changed it.
Event binding on dynamically created elements
Single element:
$(document.body).on('click','.element', function(e) { });
Child Element:
$(document.body).on('click','.element *', function(e) { });
Notice the added *
. An event will be triggered for all children of that element.
I have noticed that:
$(document.body).on('click','.#element_id > element', function(e) { });
It is not working any more, but it was working before. I have been using jQuery from Google CDN, but I don't know if they changed it.
edited Apr 22 '16 at 21:53
Peter Mortensen
13.5k1983111
13.5k1983111
answered Jan 22 '16 at 1:06
MadeInDreams
1,02011635
1,02011635
Yeap and they are not saying (document.body) its says ancestor wich could be pretty much anything
– MadeInDreams
Jan 23 '16 at 16:29
add a comment |
Yeap and they are not saying (document.body) its says ancestor wich could be pretty much anything
– MadeInDreams
Jan 23 '16 at 16:29
Yeap and they are not saying (document.body) its says ancestor wich could be pretty much anything
– MadeInDreams
Jan 23 '16 at 16:29
Yeap and they are not saying (document.body) its says ancestor wich could be pretty much anything
– MadeInDreams
Jan 23 '16 at 16:29
add a comment |
Another solution is to add the listener when creating the element. Instead of put the listener in the body, you put the listener in the element in the moment that you create it:
var myElement = $('<button/>', {
text: 'Go to Google!'
});
myElement.bind( 'click', goToGoogle);
myElement.append('body');
function goToGoogle(event){
window.location.replace("http://www.google.com");
}
Your code contains 1 mistake:myElement.append('body');
must bemyElement.appendTo('body');
. On the other hand, if there is no need for the further use of variablemyElement
it's easier and shorter this way:$('body').append($('<button/>', { text: 'Go to Google!' }).bind( 'click', goToGoogle));
– ddlab
May 11 '17 at 19:58
add a comment |
Another solution is to add the listener when creating the element. Instead of put the listener in the body, you put the listener in the element in the moment that you create it:
var myElement = $('<button/>', {
text: 'Go to Google!'
});
myElement.bind( 'click', goToGoogle);
myElement.append('body');
function goToGoogle(event){
window.location.replace("http://www.google.com");
}
Your code contains 1 mistake:myElement.append('body');
must bemyElement.appendTo('body');
. On the other hand, if there is no need for the further use of variablemyElement
it's easier and shorter this way:$('body').append($('<button/>', { text: 'Go to Google!' }).bind( 'click', goToGoogle));
– ddlab
May 11 '17 at 19:58
add a comment |
Another solution is to add the listener when creating the element. Instead of put the listener in the body, you put the listener in the element in the moment that you create it:
var myElement = $('<button/>', {
text: 'Go to Google!'
});
myElement.bind( 'click', goToGoogle);
myElement.append('body');
function goToGoogle(event){
window.location.replace("http://www.google.com");
}
Another solution is to add the listener when creating the element. Instead of put the listener in the body, you put the listener in the element in the moment that you create it:
var myElement = $('<button/>', {
text: 'Go to Google!'
});
myElement.bind( 'click', goToGoogle);
myElement.append('body');
function goToGoogle(event){
window.location.replace("http://www.google.com");
}
edited Apr 22 '16 at 21:48
Peter Mortensen
13.5k1983111
13.5k1983111
answered Oct 7 '15 at 17:43
Martin Da Rosa
34225
34225
Your code contains 1 mistake:myElement.append('body');
must bemyElement.appendTo('body');
. On the other hand, if there is no need for the further use of variablemyElement
it's easier and shorter this way:$('body').append($('<button/>', { text: 'Go to Google!' }).bind( 'click', goToGoogle));
– ddlab
May 11 '17 at 19:58
add a comment |
Your code contains 1 mistake:myElement.append('body');
must bemyElement.appendTo('body');
. On the other hand, if there is no need for the further use of variablemyElement
it's easier and shorter this way:$('body').append($('<button/>', { text: 'Go to Google!' }).bind( 'click', goToGoogle));
– ddlab
May 11 '17 at 19:58
Your code contains 1 mistake:
myElement.append('body');
must be myElement.appendTo('body');
. On the other hand, if there is no need for the further use of variable myElement
it's easier and shorter this way: $('body').append($('<button/>', { text: 'Go to Google!' }).bind( 'click', goToGoogle));
– ddlab
May 11 '17 at 19:58
Your code contains 1 mistake:
myElement.append('body');
must be myElement.appendTo('body');
. On the other hand, if there is no need for the further use of variable myElement
it's easier and shorter this way: $('body').append($('<button/>', { text: 'Go to Google!' }).bind( 'click', goToGoogle));
– ddlab
May 11 '17 at 19:58
add a comment |
I prefer using the selector and I apply it on the document.
This binds itself on the document and will be applicable to the elements that will be rendered after page load.
For example:
$(document).on("click", $(selector), function() {
// Your code here
});
2
the selector shouldn't be enclosed by $, thus the correct format will be $(document).on( "click" , "selector" , function() { // Your code here });
– autopilot
Apr 9 at 4:21
It's also pointless to wrap a jQuery object around theselector
variable, when it must either contain a string or Element object which you can just pass directly to that argument ofon()
– Rory McCrossan
Jun 20 at 14:57
add a comment |
I prefer using the selector and I apply it on the document.
This binds itself on the document and will be applicable to the elements that will be rendered after page load.
For example:
$(document).on("click", $(selector), function() {
// Your code here
});
2
the selector shouldn't be enclosed by $, thus the correct format will be $(document).on( "click" , "selector" , function() { // Your code here });
– autopilot
Apr 9 at 4:21
It's also pointless to wrap a jQuery object around theselector
variable, when it must either contain a string or Element object which you can just pass directly to that argument ofon()
– Rory McCrossan
Jun 20 at 14:57
add a comment |
I prefer using the selector and I apply it on the document.
This binds itself on the document and will be applicable to the elements that will be rendered after page load.
For example:
$(document).on("click", $(selector), function() {
// Your code here
});
I prefer using the selector and I apply it on the document.
This binds itself on the document and will be applicable to the elements that will be rendered after page load.
For example:
$(document).on("click", $(selector), function() {
// Your code here
});
edited Apr 9 at 4:48
Matthew Cliatt
2,34231733
2,34231733
answered Nov 21 '15 at 12:01
Vatsal
1,042817
1,042817
2
the selector shouldn't be enclosed by $, thus the correct format will be $(document).on( "click" , "selector" , function() { // Your code here });
– autopilot
Apr 9 at 4:21
It's also pointless to wrap a jQuery object around theselector
variable, when it must either contain a string or Element object which you can just pass directly to that argument ofon()
– Rory McCrossan
Jun 20 at 14:57
add a comment |
2
the selector shouldn't be enclosed by $, thus the correct format will be $(document).on( "click" , "selector" , function() { // Your code here });
– autopilot
Apr 9 at 4:21
It's also pointless to wrap a jQuery object around theselector
variable, when it must either contain a string or Element object which you can just pass directly to that argument ofon()
– Rory McCrossan
Jun 20 at 14:57
2
2
the selector shouldn't be enclosed by $, thus the correct format will be $(document).on( "click" , "selector" , function() { // Your code here });
– autopilot
Apr 9 at 4:21
the selector shouldn't be enclosed by $, thus the correct format will be $(document).on( "click" , "selector" , function() { // Your code here });
– autopilot
Apr 9 at 4:21
It's also pointless to wrap a jQuery object around the
selector
variable, when it must either contain a string or Element object which you can just pass directly to that argument of on()
– Rory McCrossan
Jun 20 at 14:57
It's also pointless to wrap a jQuery object around the
selector
variable, when it must either contain a string or Element object which you can just pass directly to that argument of on()
– Rory McCrossan
Jun 20 at 14:57
add a comment |
Take note of "MAIN" class the element is placed, for example,
<div class="container">
<ul class="select">
<li> First</li>
<li>Second</li>
</ul>
</div>
In the above scenario, the MAIN object the jQuery will watch is "container".
Then you will basically have elements names under container such as ul
, li
, and select
:
$(document).ready(function(e) {
$('.container').on( 'click',".select", function(e) {
alert("CLICKED");
});
});
add a comment |
Take note of "MAIN" class the element is placed, for example,
<div class="container">
<ul class="select">
<li> First</li>
<li>Second</li>
</ul>
</div>
In the above scenario, the MAIN object the jQuery will watch is "container".
Then you will basically have elements names under container such as ul
, li
, and select
:
$(document).ready(function(e) {
$('.container').on( 'click',".select", function(e) {
alert("CLICKED");
});
});
add a comment |
Take note of "MAIN" class the element is placed, for example,
<div class="container">
<ul class="select">
<li> First</li>
<li>Second</li>
</ul>
</div>
In the above scenario, the MAIN object the jQuery will watch is "container".
Then you will basically have elements names under container such as ul
, li
, and select
:
$(document).ready(function(e) {
$('.container').on( 'click',".select", function(e) {
alert("CLICKED");
});
});
Take note of "MAIN" class the element is placed, for example,
<div class="container">
<ul class="select">
<li> First</li>
<li>Second</li>
</ul>
</div>
In the above scenario, the MAIN object the jQuery will watch is "container".
Then you will basically have elements names under container such as ul
, li
, and select
:
$(document).ready(function(e) {
$('.container').on( 'click',".select", function(e) {
alert("CLICKED");
});
});
edited Apr 22 '16 at 21:56
Peter Mortensen
13.5k1983111
13.5k1983111
answered Mar 26 '16 at 2:15
Aslan Kaya
35949
35949
add a comment |
add a comment |
You can attach event to element when dynamically created using jQuery(html, attributes)
.
As of jQuery 1.8, any jQuery instance method (a method of
jQuery.fn
) can be used as a property of the object passed to the
second parameter:
function handleDynamicElementEvent(event) {
console.log(event.type, this.value)
}
// create and attach event to dynamic element
jQuery("<select>", {
html: $.map(Array(3), function(_, index) {
return new Option(index, index)
}),
on: {
change: handleDynamicElementEvent
}
})
.appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
add a comment |
You can attach event to element when dynamically created using jQuery(html, attributes)
.
As of jQuery 1.8, any jQuery instance method (a method of
jQuery.fn
) can be used as a property of the object passed to the
second parameter:
function handleDynamicElementEvent(event) {
console.log(event.type, this.value)
}
// create and attach event to dynamic element
jQuery("<select>", {
html: $.map(Array(3), function(_, index) {
return new Option(index, index)
}),
on: {
change: handleDynamicElementEvent
}
})
.appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
add a comment |
You can attach event to element when dynamically created using jQuery(html, attributes)
.
As of jQuery 1.8, any jQuery instance method (a method of
jQuery.fn
) can be used as a property of the object passed to the
second parameter:
function handleDynamicElementEvent(event) {
console.log(event.type, this.value)
}
// create and attach event to dynamic element
jQuery("<select>", {
html: $.map(Array(3), function(_, index) {
return new Option(index, index)
}),
on: {
change: handleDynamicElementEvent
}
})
.appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
You can attach event to element when dynamically created using jQuery(html, attributes)
.
As of jQuery 1.8, any jQuery instance method (a method of
jQuery.fn
) can be used as a property of the object passed to the
second parameter:
function handleDynamicElementEvent(event) {
console.log(event.type, this.value)
}
// create and attach event to dynamic element
jQuery("<select>", {
html: $.map(Array(3), function(_, index) {
return new Option(index, index)
}),
on: {
change: handleDynamicElementEvent
}
})
.appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
function handleDynamicElementEvent(event) {
console.log(event.type, this.value)
}
// create and attach event to dynamic element
jQuery("<select>", {
html: $.map(Array(3), function(_, index) {
return new Option(index, index)
}),
on: {
change: handleDynamicElementEvent
}
})
.appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
function handleDynamicElementEvent(event) {
console.log(event.type, this.value)
}
// create and attach event to dynamic element
jQuery("<select>", {
html: $.map(Array(3), function(_, index) {
return new Option(index, index)
}),
on: {
change: handleDynamicElementEvent
}
})
.appendTo("body");
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
edited Aug 13 '17 at 12:06
Milan Chheda
7,30031633
7,30031633
answered Apr 5 '17 at 7:11
guest271314
1
1
add a comment |
add a comment |
you could use
$('.buttons').on('click', 'button', function(){
// your magic goes here
});
or
$('.buttons').delegate('button', 'click', function() {
// your magic goes here
});
these two methods are equivalent but have a different order of parameters.
see: jQuery Delegate Event
delegate()
is now deprecated. Do not use it.
– Rory McCrossan
Jun 20 at 14:58
add a comment |
you could use
$('.buttons').on('click', 'button', function(){
// your magic goes here
});
or
$('.buttons').delegate('button', 'click', function() {
// your magic goes here
});
these two methods are equivalent but have a different order of parameters.
see: jQuery Delegate Event
delegate()
is now deprecated. Do not use it.
– Rory McCrossan
Jun 20 at 14:58
add a comment |
you could use
$('.buttons').on('click', 'button', function(){
// your magic goes here
});
or
$('.buttons').delegate('button', 'click', function() {
// your magic goes here
});
these two methods are equivalent but have a different order of parameters.
see: jQuery Delegate Event
you could use
$('.buttons').on('click', 'button', function(){
// your magic goes here
});
or
$('.buttons').delegate('button', 'click', function() {
// your magic goes here
});
these two methods are equivalent but have a different order of parameters.
see: jQuery Delegate Event
answered Aug 11 '16 at 16:16
Mensur Grišević
339311
339311
delegate()
is now deprecated. Do not use it.
– Rory McCrossan
Jun 20 at 14:58
add a comment |
delegate()
is now deprecated. Do not use it.
– Rory McCrossan
Jun 20 at 14:58
delegate()
is now deprecated. Do not use it.– Rory McCrossan
Jun 20 at 14:58
delegate()
is now deprecated. Do not use it.– Rory McCrossan
Jun 20 at 14:58
add a comment |
Any parent that exists at the time the event is bound and if your page was dynamically creating elements with the class name button you would bind the event to a parent which already exists
$(document).ready(function(){
//Particular Parent chield click
$(".buttons").on("click","button",function(){
alert("Clicked");
});
//Dynamic event bind on button class
$(document).on("click",".button",function(){
alert("Dymamic Clicked");
});
$("input").addClass("button");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
<input type="button" value="1">
<button>2</button>
<input type="text">
<button>3</button>
<input type="button" value="5">
</div>
<button>6</button>
add a comment |
Any parent that exists at the time the event is bound and if your page was dynamically creating elements with the class name button you would bind the event to a parent which already exists
$(document).ready(function(){
//Particular Parent chield click
$(".buttons").on("click","button",function(){
alert("Clicked");
});
//Dynamic event bind on button class
$(document).on("click",".button",function(){
alert("Dymamic Clicked");
});
$("input").addClass("button");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
<input type="button" value="1">
<button>2</button>
<input type="text">
<button>3</button>
<input type="button" value="5">
</div>
<button>6</button>
add a comment |
Any parent that exists at the time the event is bound and if your page was dynamically creating elements with the class name button you would bind the event to a parent which already exists
$(document).ready(function(){
//Particular Parent chield click
$(".buttons").on("click","button",function(){
alert("Clicked");
});
//Dynamic event bind on button class
$(document).on("click",".button",function(){
alert("Dymamic Clicked");
});
$("input").addClass("button");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
<input type="button" value="1">
<button>2</button>
<input type="text">
<button>3</button>
<input type="button" value="5">
</div>
<button>6</button>
Any parent that exists at the time the event is bound and if your page was dynamically creating elements with the class name button you would bind the event to a parent which already exists
$(document).ready(function(){
//Particular Parent chield click
$(".buttons").on("click","button",function(){
alert("Clicked");
});
//Dynamic event bind on button class
$(document).on("click",".button",function(){
alert("Dymamic Clicked");
});
$("input").addClass("button");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
<input type="button" value="1">
<button>2</button>
<input type="text">
<button>3</button>
<input type="button" value="5">
</div>
<button>6</button>
$(document).ready(function(){
//Particular Parent chield click
$(".buttons").on("click","button",function(){
alert("Clicked");
});
//Dynamic event bind on button class
$(document).on("click",".button",function(){
alert("Dymamic Clicked");
});
$("input").addClass("button");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
<input type="button" value="1">
<button>2</button>
<input type="text">
<button>3</button>
<input type="button" value="5">
</div>
<button>6</button>
$(document).ready(function(){
//Particular Parent chield click
$(".buttons").on("click","button",function(){
alert("Clicked");
});
//Dynamic event bind on button class
$(document).on("click",".button",function(){
alert("Dymamic Clicked");
});
$("input").addClass("button");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="buttons">
<input type="button" value="1">
<button>2</button>
<input type="text">
<button>3</button>
<input type="button" value="5">
</div>
<button>6</button>
answered Dec 18 '15 at 8:48
Ankit Kathiriya
985615
985615
add a comment |
add a comment |
Here is why dynamically created elements do not respond to clicks :
var body = $("body");
var btns = $("button");
var btnB = $("<button>B</button>");
// `<button>B</button>` is not yet in the document.
// Thus, `$("button")` gives `[<button>A</button>]`.
// Only `<button>A</button>` gets a click listener.
btns.on("click", function () {
console.log(this);
});
// Too late for `<button>B</button>`...
body.append(btnB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
As a workaround, you have to listen to all clicks and check the source element :
var body = $("body");
var btnB = $("<button>B</button>");
var btnC = $("<button>C</button>");
// Listen to all clicks and
// check if the source element
// is a `<button></button>`.
body.on("click", function (ev) {
if ($(ev.target).is("button")) {
console.log(ev.target);
}
});
// Now you can add any number
// of `<button></button>`.
body.append(btnB);
body.append(btnC);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
This is called "Event Delegation". Good news, it's a builtin feature in jQuery :-)
var i = 11;
var body = $("body");
body.on("click", "button", function () {
var letter = (i++).toString(36).toUpperCase();
body.append($("<button>" + letter + "</button>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
add a comment |
Here is why dynamically created elements do not respond to clicks :
var body = $("body");
var btns = $("button");
var btnB = $("<button>B</button>");
// `<button>B</button>` is not yet in the document.
// Thus, `$("button")` gives `[<button>A</button>]`.
// Only `<button>A</button>` gets a click listener.
btns.on("click", function () {
console.log(this);
});
// Too late for `<button>B</button>`...
body.append(btnB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
As a workaround, you have to listen to all clicks and check the source element :
var body = $("body");
var btnB = $("<button>B</button>");
var btnC = $("<button>C</button>");
// Listen to all clicks and
// check if the source element
// is a `<button></button>`.
body.on("click", function (ev) {
if ($(ev.target).is("button")) {
console.log(ev.target);
}
});
// Now you can add any number
// of `<button></button>`.
body.append(btnB);
body.append(btnC);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
This is called "Event Delegation". Good news, it's a builtin feature in jQuery :-)
var i = 11;
var body = $("body");
body.on("click", "button", function () {
var letter = (i++).toString(36).toUpperCase();
body.append($("<button>" + letter + "</button>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
add a comment |
Here is why dynamically created elements do not respond to clicks :
var body = $("body");
var btns = $("button");
var btnB = $("<button>B</button>");
// `<button>B</button>` is not yet in the document.
// Thus, `$("button")` gives `[<button>A</button>]`.
// Only `<button>A</button>` gets a click listener.
btns.on("click", function () {
console.log(this);
});
// Too late for `<button>B</button>`...
body.append(btnB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
As a workaround, you have to listen to all clicks and check the source element :
var body = $("body");
var btnB = $("<button>B</button>");
var btnC = $("<button>C</button>");
// Listen to all clicks and
// check if the source element
// is a `<button></button>`.
body.on("click", function (ev) {
if ($(ev.target).is("button")) {
console.log(ev.target);
}
});
// Now you can add any number
// of `<button></button>`.
body.append(btnB);
body.append(btnC);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
This is called "Event Delegation". Good news, it's a builtin feature in jQuery :-)
var i = 11;
var body = $("body");
body.on("click", "button", function () {
var letter = (i++).toString(36).toUpperCase();
body.append($("<button>" + letter + "</button>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
Here is why dynamically created elements do not respond to clicks :
var body = $("body");
var btns = $("button");
var btnB = $("<button>B</button>");
// `<button>B</button>` is not yet in the document.
// Thus, `$("button")` gives `[<button>A</button>]`.
// Only `<button>A</button>` gets a click listener.
btns.on("click", function () {
console.log(this);
});
// Too late for `<button>B</button>`...
body.append(btnB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
As a workaround, you have to listen to all clicks and check the source element :
var body = $("body");
var btnB = $("<button>B</button>");
var btnC = $("<button>C</button>");
// Listen to all clicks and
// check if the source element
// is a `<button></button>`.
body.on("click", function (ev) {
if ($(ev.target).is("button")) {
console.log(ev.target);
}
});
// Now you can add any number
// of `<button></button>`.
body.append(btnB);
body.append(btnC);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
This is called "Event Delegation". Good news, it's a builtin feature in jQuery :-)
var i = 11;
var body = $("body");
body.on("click", "button", function () {
var letter = (i++).toString(36).toUpperCase();
body.append($("<button>" + letter + "</button>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
var body = $("body");
var btns = $("button");
var btnB = $("<button>B</button>");
// `<button>B</button>` is not yet in the document.
// Thus, `$("button")` gives `[<button>A</button>]`.
// Only `<button>A</button>` gets a click listener.
btns.on("click", function () {
console.log(this);
});
// Too late for `<button>B</button>`...
body.append(btnB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
var body = $("body");
var btns = $("button");
var btnB = $("<button>B</button>");
// `<button>B</button>` is not yet in the document.
// Thus, `$("button")` gives `[<button>A</button>]`.
// Only `<button>A</button>` gets a click listener.
btns.on("click", function () {
console.log(this);
});
// Too late for `<button>B</button>`...
body.append(btnB);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
var body = $("body");
var btnB = $("<button>B</button>");
var btnC = $("<button>C</button>");
// Listen to all clicks and
// check if the source element
// is a `<button></button>`.
body.on("click", function (ev) {
if ($(ev.target).is("button")) {
console.log(ev.target);
}
});
// Now you can add any number
// of `<button></button>`.
body.append(btnB);
body.append(btnC);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
var body = $("body");
var btnB = $("<button>B</button>");
var btnC = $("<button>C</button>");
// Listen to all clicks and
// check if the source element
// is a `<button></button>`.
body.on("click", function (ev) {
if ($(ev.target).is("button")) {
console.log(ev.target);
}
});
// Now you can add any number
// of `<button></button>`.
body.append(btnB);
body.append(btnC);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
var i = 11;
var body = $("body");
body.on("click", "button", function () {
var letter = (i++).toString(36).toUpperCase();
body.append($("<button>" + letter + "</button>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
var i = 11;
var body = $("body");
body.on("click", "button", function () {
var letter = (i++).toString(36).toUpperCase();
body.append($("<button>" + letter + "</button>"));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button>A</button>
edited Oct 19 '17 at 12:16
answered Sep 16 '17 at 7:01
leaf
11k43969
11k43969
add a comment |
add a comment |
Try like this -
$(document).on( 'click', '.click-activity', function () { ... });
add a comment |
Try like this -
$(document).on( 'click', '.click-activity', function () { ... });
add a comment |
Try like this -
$(document).on( 'click', '.click-activity', function () { ... });
Try like this -
$(document).on( 'click', '.click-activity', function () { ... });
answered Jun 30 '16 at 6:25
Rohit Suthar
2,49912936
2,49912936
add a comment |
add a comment |
Use the .on()
method of jQuery http://api.jquery.com/on/ to attach event handlers to live element.
Also as of version 1.9 .live()
method is removed.
add a comment |
Use the .on()
method of jQuery http://api.jquery.com/on/ to attach event handlers to live element.
Also as of version 1.9 .live()
method is removed.
add a comment |
Use the .on()
method of jQuery http://api.jquery.com/on/ to attach event handlers to live element.
Also as of version 1.9 .live()
method is removed.
Use the .on()
method of jQuery http://api.jquery.com/on/ to attach event handlers to live element.
Also as of version 1.9 .live()
method is removed.
answered Nov 30 '16 at 9:07
Kalpesh Patel
2,23921846
2,23921846
add a comment |
add a comment |
Bind the event to a parent which already exists:
$(document).on("click", "selector", function() {
// Your code here
});
add a comment |
Bind the event to a parent which already exists:
$(document).on("click", "selector", function() {
// Your code here
});
add a comment |
Bind the event to a parent which already exists:
$(document).on("click", "selector", function() {
// Your code here
});
Bind the event to a parent which already exists:
$(document).on("click", "selector", function() {
// Your code here
});
answered Jun 8 at 2:29
truongnm
98321027
98321027
add a comment |
add a comment |
More flexible solution to create elements and bind events (source)
// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});
//creating a dynamic button
var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });
// binding the event
$btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
console.log('clicked');
});
// append dynamic button to the dynamic container
$div.append($btn);
// add the dynamically created element(s) to a static element
$("#box").append($div);
Note: This will create an event handler instance for each element (may affect performance when used in loops)
add a comment |
More flexible solution to create elements and bind events (source)
// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});
//creating a dynamic button
var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });
// binding the event
$btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
console.log('clicked');
});
// append dynamic button to the dynamic container
$div.append($btn);
// add the dynamically created element(s) to a static element
$("#box").append($div);
Note: This will create an event handler instance for each element (may affect performance when used in loops)
add a comment |
More flexible solution to create elements and bind events (source)
// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});
//creating a dynamic button
var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });
// binding the event
$btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
console.log('clicked');
});
// append dynamic button to the dynamic container
$div.append($btn);
// add the dynamically created element(s) to a static element
$("#box").append($div);
Note: This will create an event handler instance for each element (may affect performance when used in loops)
More flexible solution to create elements and bind events (source)
// creating a dynamic element (container div)
var $div = $("<div>", {id: 'myid1', class: 'myclass'});
//creating a dynamic button
var $btn = $("<button>", { type: 'button', text: 'Click me', class: 'btn' });
// binding the event
$btn.click(function () { //for mouseover--> $btn.on('mouseover', function () {
console.log('clicked');
});
// append dynamic button to the dynamic container
$div.append($btn);
// add the dynamically created element(s) to a static element
$("#box").append($div);
Note: This will create an event handler instance for each element (may affect performance when used in loops)
edited Apr 26 at 13:09
answered Apr 18 '17 at 19:47
Prasad De Silva
3011414
3011414
add a comment |
add a comment |
I prefer to have event listeners deployed in a modular function fashion rather than scripting a document
level event listener. So, I do like below. Note, you can't oversubscribe an element with the same event listener so don't worry about attaching a listener more than once - only one sticks.
var iterations = 4;
var button;
var body = document.querySelector("body");
for (var i = 0; i < iterations; i++) {
button = document.createElement("button");
button.classList.add("my-button");
button.appendChild(document.createTextNode(i));
button.addEventListener("click", myButtonWasClicked);
body.appendChild(button);
}
function myButtonWasClicked(e) {
console.log(e.target); //access to this specific button
}
I prefer this implementation; I just have to set up a call back
– William
Oct 22 at 10:18
add a comment |
I prefer to have event listeners deployed in a modular function fashion rather than scripting a document
level event listener. So, I do like below. Note, you can't oversubscribe an element with the same event listener so don't worry about attaching a listener more than once - only one sticks.
var iterations = 4;
var button;
var body = document.querySelector("body");
for (var i = 0; i < iterations; i++) {
button = document.createElement("button");
button.classList.add("my-button");
button.appendChild(document.createTextNode(i));
button.addEventListener("click", myButtonWasClicked);
body.appendChild(button);
}
function myButtonWasClicked(e) {
console.log(e.target); //access to this specific button
}
I prefer this implementation; I just have to set up a call back
– William
Oct 22 at 10:18
add a comment |
I prefer to have event listeners deployed in a modular function fashion rather than scripting a document
level event listener. So, I do like below. Note, you can't oversubscribe an element with the same event listener so don't worry about attaching a listener more than once - only one sticks.
var iterations = 4;
var button;
var body = document.querySelector("body");
for (var i = 0; i < iterations; i++) {
button = document.createElement("button");
button.classList.add("my-button");
button.appendChild(document.createTextNode(i));
button.addEventListener("click", myButtonWasClicked);
body.appendChild(button);
}
function myButtonWasClicked(e) {
console.log(e.target); //access to this specific button
}
I prefer to have event listeners deployed in a modular function fashion rather than scripting a document
level event listener. So, I do like below. Note, you can't oversubscribe an element with the same event listener so don't worry about attaching a listener more than once - only one sticks.
var iterations = 4;
var button;
var body = document.querySelector("body");
for (var i = 0; i < iterations; i++) {
button = document.createElement("button");
button.classList.add("my-button");
button.appendChild(document.createTextNode(i));
button.addEventListener("click", myButtonWasClicked);
body.appendChild(button);
}
function myButtonWasClicked(e) {
console.log(e.target); //access to this specific button
}
var iterations = 4;
var button;
var body = document.querySelector("body");
for (var i = 0; i < iterations; i++) {
button = document.createElement("button");
button.classList.add("my-button");
button.appendChild(document.createTextNode(i));
button.addEventListener("click", myButtonWasClicked);
body.appendChild(button);
}
function myButtonWasClicked(e) {
console.log(e.target); //access to this specific button
}
var iterations = 4;
var button;
var body = document.querySelector("body");
for (var i = 0; i < iterations; i++) {
button = document.createElement("button");
button.classList.add("my-button");
button.appendChild(document.createTextNode(i));
button.addEventListener("click", myButtonWasClicked);
body.appendChild(button);
}
function myButtonWasClicked(e) {
console.log(e.target); //access to this specific button
}
answered Jun 8 at 2:53
Ron Royston
5,77032538
5,77032538
I prefer this implementation; I just have to set up a call back
– William
Oct 22 at 10:18
add a comment |
I prefer this implementation; I just have to set up a call back
– William
Oct 22 at 10:18
I prefer this implementation; I just have to set up a call back
– William
Oct 22 at 10:18
I prefer this implementation; I just have to set up a call back
– William
Oct 22 at 10:18
add a comment |
This is done by event delegation. Event will bind on wrapper-class element but will be delegated to selector-class element. This is how it works.
$('.wrapper-class').on("click", '.selector-class', function() {
// Your code here
});
Note:
wrapper-class element can be anything ex. document, body or your wrapper. Wrapper should already exist.
add a comment |
This is done by event delegation. Event will bind on wrapper-class element but will be delegated to selector-class element. This is how it works.
$('.wrapper-class').on("click", '.selector-class', function() {
// Your code here
});
Note:
wrapper-class element can be anything ex. document, body or your wrapper. Wrapper should already exist.
add a comment |
This is done by event delegation. Event will bind on wrapper-class element but will be delegated to selector-class element. This is how it works.
$('.wrapper-class').on("click", '.selector-class', function() {
// Your code here
});
Note:
wrapper-class element can be anything ex. document, body or your wrapper. Wrapper should already exist.
This is done by event delegation. Event will bind on wrapper-class element but will be delegated to selector-class element. This is how it works.
$('.wrapper-class').on("click", '.selector-class', function() {
// Your code here
});
Note:
wrapper-class element can be anything ex. document, body or your wrapper. Wrapper should already exist.
edited Jul 24 at 8:18
answered Jun 14 at 11:15
Must Keem J
943717
943717
add a comment |
add a comment |
<html>
<head>
<title>HTML Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="hover-id">
Hello World
</div>
<script>
jQuery(document).ready(function($){
$(document).on('mouseover', '#hover-id', function(){
$(this).css('color','yellowgreen');
});
$(document).on('mouseout', '#hover-id', function(){
$(this).css('color','black');
});
});
</script>
</body>
</html>
1
While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
– Palec
Sep 30 '17 at 11:07
add a comment |
<html>
<head>
<title>HTML Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="hover-id">
Hello World
</div>
<script>
jQuery(document).ready(function($){
$(document).on('mouseover', '#hover-id', function(){
$(this).css('color','yellowgreen');
});
$(document).on('mouseout', '#hover-id', function(){
$(this).css('color','black');
});
});
</script>
</body>
</html>
1
While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
– Palec
Sep 30 '17 at 11:07
add a comment |
<html>
<head>
<title>HTML Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="hover-id">
Hello World
</div>
<script>
jQuery(document).ready(function($){
$(document).on('mouseover', '#hover-id', function(){
$(this).css('color','yellowgreen');
});
$(document).on('mouseout', '#hover-id', function(){
$(this).css('color','black');
});
});
</script>
</body>
</html>
<html>
<head>
<title>HTML Document</title>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
</head>
<body>
<div id="hover-id">
Hello World
</div>
<script>
jQuery(document).ready(function($){
$(document).on('mouseover', '#hover-id', function(){
$(this).css('color','yellowgreen');
});
$(document).on('mouseout', '#hover-id', function(){
$(this).css('color','black');
});
});
</script>
</body>
</html>
answered Sep 27 '17 at 15:42
Fakhrul Hasan
444
444
1
While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
– Palec
Sep 30 '17 at 11:07
add a comment |
1
While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
– Palec
Sep 30 '17 at 11:07
1
1
While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
– Palec
Sep 30 '17 at 11:07
While this code snippet may solve the problem, it doesn't explain why or how it answers the question. Please include an explanation for your code, as that really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.
– Palec
Sep 30 '17 at 11:07
add a comment |
I was looking a solution to get $.bind
and $.unbind
working without problems in dynamically added elements.
As on() makes the trick to attach events, in order to create a fake unbind on those I came to:
const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );
// unbind the click
$('body').on('click', 'button.send', function(){} );
The unbinding does not work, this simply adds another event which points to an empty function...
– Fabian Bigler
Nov 9 at 11:28
add a comment |
I was looking a solution to get $.bind
and $.unbind
working without problems in dynamically added elements.
As on() makes the trick to attach events, in order to create a fake unbind on those I came to:
const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );
// unbind the click
$('body').on('click', 'button.send', function(){} );
The unbinding does not work, this simply adds another event which points to an empty function...
– Fabian Bigler
Nov 9 at 11:28
add a comment |
I was looking a solution to get $.bind
and $.unbind
working without problems in dynamically added elements.
As on() makes the trick to attach events, in order to create a fake unbind on those I came to:
const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );
// unbind the click
$('body').on('click', 'button.send', function(){} );
I was looking a solution to get $.bind
and $.unbind
working without problems in dynamically added elements.
As on() makes the trick to attach events, in order to create a fake unbind on those I came to:
const sendAction = function(e){ ... }
// bind the click
$('body').on('click', 'button.send', sendAction );
// unbind the click
$('body').on('click', 'button.send', function(){} );
answered May 18 at 0:13
Evhz
3,43842343
3,43842343
The unbinding does not work, this simply adds another event which points to an empty function...
– Fabian Bigler
Nov 9 at 11:28
add a comment |
The unbinding does not work, this simply adds another event which points to an empty function...
– Fabian Bigler
Nov 9 at 11:28
The unbinding does not work, this simply adds another event which points to an empty function...
– Fabian Bigler
Nov 9 at 11:28
The unbinding does not work, this simply adds another event which points to an empty function...
– Fabian Bigler
Nov 9 at 11:28
add a comment |
protected by lifetimes Mar 24 '14 at 10:09
Thank you for your interest in this question.
Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).
Would you like to answer one of these unanswered questions instead?
11
Here's a detailed article on how to bind click event for dynamic element goo.gl/zlEbnv
– Satinder singh
Aug 17 '15 at 5:14