click() assigned in document.ready in jQuery - javascript

Do assignments in document.ready (click(fn) specifically) apply to newly appended elements that match the selector?
If not, how can I assign it to this new elements? Do I have to write the assignment after every append or is there a better way?

You are looking for the live functionality. Per the manual:
Binds a handler to an event (like click) for all current - and future - matched element. Can also bind custom events.
So if you do this:
$(document).ready(function() {
$('div.test').live('click', function() { alert('yipee!'); });
$('body').append('<div class="test">Click me!</div>');
});
When you click on the div you will get the alert even though it was added after the event was bound.

Related

How to select elements added via javascript [duplicate]

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.

on() function in jquery not working [duplicate]

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

jquery issue with on and live

I have the following code:
var $reviewButton = $('span.review_button');
$reviewButton
.live('click',
function(){
$('#add_reviews').show();
}
)
Later in the script, I use an AJAX call to load some content and another instance of $('span.review_button') enters the picture. I updated my code above to use '.live' because the click event was not working with the AJAX generated review button.
This code works, as the .live(click //) event works on both the static 'span.review_button' and the AJAX generated 'span.review_button'
I see however that .live is depracated so I have tried to follow the jquery documentations instructions by switching to '.on' but when I switch to the code below, I have the same problem I had before switching to '.live' in which the click function works with the original instance of 'span.review_button' but not on the AJAX generated instance:
var $reviewButton = $('span.review_button');
$reviewButton
.on('click',
function(){
$('#add_reviews').show();
}
)
Suggestions?
The correct syntax for event delegation is:
$("body").on("click", "span.review_button", function() {
$("#add_reviews").show();
});
Here instead of body you may use any static parent element of "span.review_button".
Attention! As discussed in the comments, you should use string value as a second argument of on() method in delegated events approach, but not a jQuery object.
This is because you need to use the delegation version of on().
$("#parentElement").on('click', '.child', function(){});
#parentElement must exist in the DOM at the time you bind the event.
The event will bubble up the DOM tree, and once it reaches #parentElement, it is checked for it's origin, and if it matches .child, executes the function.
So, with this in mind, it's best to bind the event to the closest parent element existing in the DOM at time of binding - for best performance.
Set your first selector (in this case, div.content) as the parent container that contains the clicked buttons as well as any DOM that will come in using AJAX. If you have to change the entire page for some reason, it can even be change to "body", but you want to try and make the selector as efficient as possible, so narrow it down to the closest parent DOM element that won't change.
Secondly, you want to apply the click action to span.review_button, so that is reflected in the code below.
// $('div.content') is the content area to watch for changes
// 'click' is the action applied to any found elements
// 'span.review_button' the element to apply the selected action 'click' to. jQuery is expecting this to be a string.
$('div.content').on('click', 'span.review_button', function(){
$('#add_reviews').show();
});

Rebind a JQuery function to an input field after innerHTML command

Im using JQuery to check the file size and name from an html file input field. The input field is:
<div id="uploadFile_div">
<input name="source" id="imageFile" type="file" style ="border: 1px solid #576675;">
</div>
And the JQuery:
$(document).ready(function(){
$('#imageFile').bind('change', function() {
alert("Test");
//.... perform input checks...//
});
});
Now, I have a selection box, where the user choose between image file or video file, and based on it I send the file to different servers and also perform appropriate checks. In order to reset the input field (I do it when the user changes the selection box from Video to Image and vise versa) I use this JavaScript trick:
document.getElementById('uploadFile_div').innerHTML = document.getElementById('uploadFile_div').innerHTML;
But After 1 execution of this JavaScript, The JQuery isn't binded and I don't see the "Test" alert when I select files.
How can i rebind the JQuery ?
Thanks.
You could use a delegated event handler, binding the event to the parent div:
$('#uploadFile_div').on('change','#imageFile', function() {
// etc
Demo: http://jsfiddle.net/SfgpS/
(If you're using a version of jQuery older than 1.7 use .delegate() instead of .on(). If you're using a really old version of jQuery use .live().)
When you rewrite the .innerHTML of the container that effectively erases the old input element including event handlers that were bound to it, and then creates a new input. So you could re-run your original .bind() statement at that point to bind a handler to the new input.
With a delegated event handler as for that syntax of .on() you bind the handler to the container, i.e., to the div in this case. Events that happen to the container's child(ren) bubble up to the container (and then right on up to the document). So in this case when a change event reaches the div jQuery checks whether it originated with an element matching the selector from the second parameter of .on() and if so calls the your handler function. This lets you handle events on elements that don't exist at the time you create the handler. It doesn't matter if you remove and re-add the child elements because the handler was bound to the container.
(Note that if you leave out that second parameter to .on() it creates a non-delegated handler just the same as .bind().)
Why not just wrap the whole mess up in a function you can call both onReady and then whenever you want to reset the upload form?
var resetUpload = function() {
document.getElementById('uploadFile_div').innerHTML = document.getElementById('uploadFile_div').innerHTML;
$('#imageFile').bind('change', function() {
alert("Test");
//.... perform input checks...//
});
}
// run on ready
$(document).ready(function () {
resetUpload();
});
What version of jQuery are you using?
You could use .live() or .on() (jQuery >= 1.7) instead of .bind()

jquery using $.on for added dom elements?

I am a bit confused, I have a bunch of elements that get added via jquery using a ajax call and I want to attach a click handler to them (there could be a lot).
But I have no idea how to even begin this, I looked at .on and it is really confusing. I want to attach a click event handler for a certain class so that when I click on it, I get the this.id and then do stuff with it.
What you're trying to do is called event delegation.
You want to set the event listener on a higher element in the DOM that'll never change, but only fire off the event handler if the child element that has been clicked matches a specific selector.
Here's how it's done with jQuery's .on():
$(document).on('click', '.your-selector', function(){
alert(this.id);
});
P.S. You could probably apply the event listener to an element lower down in the DOM tree...
This will get you the id of a clicked element with the class "test"...
$(".test").on("click", function() {
var id = $(this).attr("id")
});
You'll need to run that after the ajax call returns. It will only bind the click event to elements that exist when it runs, so it's no good at document.ready.

Categories