This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
This thing is driving me nuts.
So I load some simple HTML via AJAX and once it's loaded on the DOM I do this.
$('#wrap a.link').click(function(e) {
e.preventDefault();
alert("asdasdad");
});
It simply does not prevent the link from navigating to the url in the href attribute.
My syntax seems right and I've made sure the element is in the DOM and that the function finds the a.link element.
$("#wrap a.link").each(function(key, value) {
console.log("found a link"); // this shows up in the console
});
I have also tried using off() and stopImmediatePropagation() just in case some other event may be interfering, but nothing. I've also tried binding the event inside the each() loop with the same result.
What could be causing this behaviour?
Bind the events to the body for dynamic elements:
$('body').on('click','#wrap a.link',function(e) {
e.preventDefault()
});
Use event delegation:
$(document).on('click', '#wrap a.link', function(e) {
e.preventDefault();
alert("asdasdad");
});
Caution:
Keep your IDs unique.
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
We have an external js file loaded on our static html page with a jQueryUI dialog opening a url with jQuery.load() from a button click. Inside the ajax content returned is a handful of input elements, all number type. We need to bind the keydown and change events to the number inputs, however it's not binding since the .bind() is happening before the elements are in the DOM from the ajax result. We know about .on() but having an awfully hard time wiring it up. I know we're missing something simple; any suggestions?
Basic Fiddle recreation: http://jsfiddle.net/jbwebtech/wvufLket/
There's nothing too hard to grasp that it's not already explained pretty decently inside the jQuery .on() documentation: http://api.jquery.com/on/#direct-and-delegated-events
http://learn.jquery.com/events/event-delegation/
$(staticElementParent).on("event1 event2", dynamicElement, function(){ /*stuff*/ });
In your specific case:
fiddle demo
var ajax_content = '<input type="number"><br><input type="number"><br><input type="number"><br><input type="number">';
$(function () {
console.log('jquery ready');
$("body").on('input', 'input[type=number]', function (event) {
console.log('on() input successful');
});
// "AJAX" ;)
$('button').click(function(){
$('#ajax_container').html(ajax_content);
})
});
As always, read the Docs
Can't you just put your bind the callback of the .load() function? Or if you can't(im not sure), you can change a variable in the callback and check if it's loaded in the bind.
Or you can put the bind in the file that loaded with jquery(at the end of it).
Sorry, i can't comment yet.
This question already has answers here:
adding jQuery click events to dynamically added content
(4 answers)
Closed 9 years ago.
I have a simple code that check a select change and alert a message. This is working ok but when I insert new .select-payment elements on the page this method is only available to the first one and not the ones created via javascript
$(document).ready(function() {
return $(".select-payment").on("change", function() {
return alert("hello");
});
});
Any idea how to make it work for any element that is added after the page is loaded that has a .select-payment class?
$(document).on("change", ".select-payment", function() {
alert("hello");
});
Also returning from within the change handler hardly makes sense, even less, returning the result of an alert.
You could use event delegation like below,
$(document).on('change', '.select-payment', function () {..
Replace the document with any closeby container that exist in DOM when executing the above line
Event delegation binds the event to the parent element and executes the handler when event.target matches the specified selector.
When targeting dynamically created elements, you need to use .on()'s delegated syntax:
$(document).on("change", ".select-payment", function() {
From the docs:
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().
To ensure the elements are present and can be selected, perform event
binding inside a document ready handler for elements that are in the
HTML markup on the page. If new HTML is being injected into the page,
select the elements and attach event handlers after the new HTML is
placed into the page.
why are you putting return statement ? You must attach your event handler to the document and not the existing .select-payment.
Try this : $(document).on("change",".select-payment",function(){...});
$(document).on("change", ".select-payment", function () {
alert("hello"); }
);
You can replace document with any closer parent element which will always exist in DOM for better performance. Like
$('#closestId').on("change", ".select-payment", function () {
alert("hello");
}
);
if you use $("document") jQuery will search for a node/tag named as document like and wont find anything as document is actually an object.
But you could use $("body") as body is a node/element of DOM.
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
I am adding dynamic content to a php page using jQuery. I don't have a problem adding the content I just can't seem to find a way to make the new content respond to a click event.
For example (I'm using a div here but could be a button or other type).
$("#oldstuff").after('<div id="newstuff">Some content that should respond to click event</div>');
Edit:
I am currently using jquery 1.9.1, I was using 1.6.2 but I am checking out magnific-popup which required a newer jquery version.
I didn't post my failed attempts (
$("#newstuff").click(function() {...
$("#newstuff").live('click', function() {...
binding the click event, etc.
because I assumed that I am missing something fundamental that a more seasoned jQuery user would spot without the noise of broken code.
You can attach a click event before inserting the element into the DOM:
$('<div id="newstuff">...</div>').click(function(){
//do something
}).insertAfter('#oldstuff');
can't seem to find a way to make the new content respond to a click event.
You have to do event delegation
$("#oldstuff").on("click", '#newstuff',function(){
alert( $(this).text() );
});
What you need is to attach the event to the parent element.
HTML:
<div id="parent">
<div class="thediv">Hello</div>
</div>
JavaScript:
function addDiv() {
var div = document.createElement('div');
div.className = 'thediv';
document.getElementById('parent').appendChild(div);
}
$('#parent').on('click', '.thediv', function() {
// ...
});
See if this technique works.
It is probably you are binding event before attaching DOM and also in latest version of jquery library live method is deprecated so try to bind click even after attaching DOM or you can use following code...
first add DOM.
$("#oldstuff").after('<div id="newstuff">Some content that should respond to click event</div>');
and then bind event.
$('#newstuff').on('click',function(){alert('do your stuff!')});
Or
$('#newstuff').click(function(){alert('do your stuff!')});
Try this
$("#yourElementId").live("click",function(){
alert( $(this).text() );
});
As .click is not working after loading dom or dynamically created element
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 9 years ago.
I am making dynamic buttons using jQuery. Now I want to use this buttons as any other buttons. Here is my HTML:
<label class='twobuttons'><div id="submit-button" >GO!</div></label>
<div id='result'></div>
And here is my JavaScript:
$(document).ready(function(){
$('#submit-button').click(function(){
$('#result').append("<label><div id='share' class='longbutton'>Share this route</div></label>");
$('#result').append("<label><div id='goback' class='longbutton'>Create another one !</div></label>");
});
$('#share').on("click",function(){
alert('hi');
});
$('#goback').on("click",function(){
alert('hello');
})
});
I'm specifically having trouble with the $('#share').on( part.
I tried the on() function as suggested here. But it is not working. Here is the fiddle of my code. Please correct me if I am wrong somewhere.
That isn't how .on() works, if you are dynamically creating elements, you can't bind an event handler to it, because at the point the code runs (document.ready), the element doesn't exist. So to "get around" that, you bind the event to a parent element (that exists) and then add the actual element you'll be clicking on as a parameter like this:
$('body').on("click", "#share", function(){
alert('hi');
});
$('body').on("click", "#goback",function(){
alert('hello');
})
DEMO
You should setup event delegation on #result instead, because by the time you're trying to setup the click handlers on #share, the element itself has not been added yet.
$('#result').on('click', '#share', function() {
// your code here
});
Try not to bind the event handler to $(document) by default; the closest element that will not get removed is the prime candidate.
Alternatively, only bind the click handlers after you've added the new elements.
Update
You're appending elements with a fixed identifier at every click of your button; note that identifiers should be unique per document, so you should make sure that the action is performed at most once.
The way the .on() method works changes according to how you use it. In your example the .on() method behaves similar to bind and will only work on elements that already exist.
Try this:
$(document).on("click",'#share',function(){
alert('hi');
});
DEMO
It's not enough to use .on(). You have to use event delegation with an element (such as document) that existed before your dynamically-created elements:
$(document).on('click', '#share', function () {
alert('hi');
});
(Based on your fiddle, you can use #result instead of document.)
Fiddle
This question already has answers here:
Responding to click event of element added to document after page load
(6 answers)
Closed 8 years ago.
I add a delete button dynamically to the page once the user uploads an image.
$('.galleryImage .delete').bind('click', function() {
//do delete
}
The above does not work.
As I understand it, it's because the delete button is added to the page after creation.
I've tried
$('body').on('click', '.galleryImage .delete', function() {
But this only works with jquery 1.7+ and I need to use 1.6.
Any ideas how I can get this to work?
As you want to use in jQuery 1.6 so you can use .delegate() event handling.
$('.galleryImage').delegate('.delete', 'click', function() {
but would be better if you use jquery 1.7
and .on() event handler
$('.galleryImage').on('click', '.delete',function() {
According to comment
if .galleryImage is dynamically added then you should use a Static-element that is container of .galleryImage, that means the container should not dynamic.
Use delegate():
$('.galleryImage').delegate('.delete', 'click', function() {
//do delete
}
Or use on() with a delegated selector if you are using jQuery 1.7+:
$('.galleryImage').on('click', '.delete', function() {
//do delete
}
If the .galleryImage element is also dynamically added, you should use the selector which relates to the nearest non-dynamic element.
Do not use live()! It is slow, outdated and deprecated.
instead of on use delegate or live methods
http://api.jquery.com/live/
http://api.jquery.com/delegate/