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.
Related
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 2 years ago.
I am injecting some html strings to create buttons, however they jquery events don't fire after they have been created. I was told they needed to be "initialized" but cannot find an example.
$('#parent_div).html(<div class="clickable-button">click me here</div>);
will create:
<div id='parent_div'>
<div class="clickable-button">click me here</div>
</div>
And my usual jquery doesn't fire when clicked.
$('.clickable-button').on('click', function (){
console.log('clicked');
}
I got it to work by using a parent that existed before the injection with on()
$('#parent_div').on('click', '.clickable-button', function(){
console.log('clicked');
}
But it seems like there should be a better way to handle this because I don't always know what the parent is and I don't want to hard code new jquery every time I inject something. How do people usually handle this problem?
You can listen at the document level in that case you dont know whats the parent element
$(document.body).on('click', '.clickable-button', function(){
console.log('clicked');
}
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.
This question already has answers here:
Adding event listeners to dynamically added elements using jQuery [duplicate]
(4 answers)
Closed 8 years ago.
It's very easy to event-handle when dealing with items the document has from the get go:
$(document).ready(function() {
$('.element-in-question').on("event", function (event) {
//do what you need to do during the event
});
});
My problem is how would I best deal with dynamic elements. For example, let's say I dynamically load notifications, some of which are friend requests during an AJAX request. Would I create the event-handler in the success callback, or would I do it somewhere else?
The way I would currently go about it:
$(document).ready(function() {
$.ajax({
url: '/friendships/requests',
type: 'GET',
success: function(responseData) {
//dynamically create your elements (with classes accepted and rejected)
$('.accepted, .rejected').on("click", function(event) {
//do what is needed in this event
});
}
});
});
Is this the idiomatic way to go about it, or is there another way I probably should be going about it?
use jquery's "on" merhod to bind event handler to parent element (which will not change) and pass a selector of the element you want to listen to:
$('.parent').on('event', '.child', handlerFunction);
If you dynamically create an element, such as a 'button', that was not on the page before, handle it like this:
$(function() {
(function() {
$('body').append('<button id="newButton">Hello World!</button>');
})();
$('body').on('click','#newButton',function() {
console.log($(this).html()); //"Hello World!"
});
});
I think this is the (partly) right approach. You cannot and should not apply eventhandlers to objects that might or might not be available, even if possible.
If the situation would involve 10000 different eventhandlers, they should be only available when present in dom. When removed the eventhandler should be removed as well.
The way you do it is rudimentary but correct.
2 other thoughts. If you bind the listener in the ajax callback you might add to the "stack" of events, since they are not replaced. Not a good thing. If the ajax query will happend more than once, do not add it again, if not removed first.
Another aproach might be to just add them to all pages, if this is a small page/application and first check that the element exist. Like so:
if ($('#id').size() > 0) {
// bind events for #id here
}
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:
Closed 10 years ago.
Possible Duplicate:
Binding dynamically created elements in jQuery
Is there a way I can change the following code:
$('#city')
.focus(function () {
$('option[value="99"]', this).remove();
store.setItem($(this).attr('id'), $(this).val());
})
.change(function () {
store.setItem($(this).attr('id'), $(this).val());
$(this).attr("title", $("option:selected", this).attr("title"));
$('#detailData').html("");
});
So that it works for selects even if they have not yet been created as long as they have the class "update-title". for example:
<select class="update-title">
I saw some implementation using live but someone said it was not good to use. Also is there much of an overhead doing this. Would it be better for me to add the code after I am sure the selects have been created with document.ready() ?
Have a look at on. This is a replacement for live which would do this for you.
You need on:
$(document).on('change', '.update-title', function(event){
// your business here
});
This way the document listens for any events triggered on .update-title elements, wether they were there at document load or not.
Best way is to use delegation - so you bind the event handler to a parent element that exists at the time the dom is loaded - It will in turn listen for events on the given elements and handle them
ex with jQuery 1.7+
$('body').on('click','.update-title', function(){ // <-- all click events will now bubble
// up to body - and it will listen for events from .update-title
// code here
});
It is best practice to bind the event handler to the closest parent at dom load as you can see the overhead in binding to the body/document - all click events will bubble up - wheareas if you bind to a parent element only those inside that element will bubble up.
Yes,you sure thtat the selects have been created with document.ready(), if the html is not loaded in ajax