This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 7 years ago.
Why is the link not working if the link is created with javascript?
It only works if I make the link without the html() output
Not working
$(".link").on('click', function(){
alert('Hello');
});
$("#link").html('Link');
<div id="link"></div>
Working
$(".link").on('click', function(){
alert('Hello');
});
Link
Your code doesn't work because event is bound when the element does not exists in DOM
Wrap your code in ready or move the code to the bottom of body so your code will run when the DOM is completely parsed
Use event delegation to bind event on dynamically created elements.(This will make the first option above optional)
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$(document).ready(function() {
$("#link").on('click', '.link', function() {
$("#link").append(' Link ');
});
$("#link").html('Link');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div id="link"></div>
Change the order of the calls. The element with class of .link does not exist in the DOM yet when you attach the handler. You must add the link via the html call on the div before you can attach a handler to it with the on method. See below for a complete, working example.
$("#link").html('Link');
$(".link").on('click', function(){
alert('Hello');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="link"></div>
Related
This question already has answers here:
Does jQuery.on() work for elements that are added after the event handler is created?
(2 answers)
Closed 7 years ago.
I need to add a class to an element on the fly. But after adding the class, all events, related to this class, work only from elements, whose classes already have been defined when the document was loaded.
Consider this example.
Text 1 has no class yet, while Text 2 does. When the button is clicked, myClass is assigned to Text 1, so both, Text 1 and Text 2, are now from class myClass.
An alert box should appear, when an element of myClass is clicked, but this event is only triggered when Text 2 is clicked. The element, whose class was already defined when the document was loaded.
<button>Add class to Text 1</button><br />
Text 1 <br />
Text 2
<script>
$(document).ready(function() {
$("button").click(function() {
$("a").addClass("myClass");
});
$(".myClass").click(function() {
alert("clicked!");
});
});
</script>
Here is a fiddle: https://jsfiddle.net/zx8wuy97/
One option would be to use event delegation. In doing so, the event is attached to a constant parent element, and the class of the descendant element is checked when the event is actually fired (rather than when the event is attached).
You should attach the event listener to a common ancestor element, but in this case I attached it to document since you didn't provide any additional markup.
Updated Example
$(document).on('click', ".myClass", function() {
alert("clicked!");
});
$(".myClass").click(function() {
alert("clicked!");
});
// Is the same as:
$("body").on("click", ".myClass",function() {
alert("clicked!");
});
As with dynamically loaded content, this will fix said problem.
In jQuery, how to attach events to dynamic html elements?
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 8 years ago.
please help me out with this issue: both .click and .on are not working when i am clicking on appended
$(document).ready(function() {
$( ".cooldiv" ).click(function() {
alert(1);
});
$(".cooldiv").on('click', function(){
alert(1);
});
$("#fields_count").change(function() {
var $newDiv = $('<div class="cooldiv">i am cooldiv</div>');
//$($newDiv).addClass('cooldiv');
$("#testdivs").append($newDiv);
});
});
html is:
<div id="testdivs"><div class='cooldiv'>qwdqwdwef</div></div>
<input type="text" size="3" id="fields_count" name="fields_count" value="3">
when i am clicking on a div containing 'qwdqwdwef', alert comes, but it does not when clicking on appended div's of the same class.
Any ideas?
Try to use event-delegation, you may ask why should i use delegation here..? The answer is while binding events to the element with the class .cooldiv, it would not be available in the Dom. so event wont get bound to that. So we have to bye pass the situation by means of event delegation
$('#testdivs').on('click','.cooldiv',function(){
alert(1);
});
You need to use delegation. Because your new element was not there when you added the click event handler you need to use a delegated event handler.
Try this instead:
$(document).on('click', '.cooldiv', function(){
alert(1);
});
You might want to check out the jQuery documentation about .on().
You need event delegation.
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
try this:
$("#testdivs").on('click','.cooldiv', function(){
alert(1);
});
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 8 years ago.
I am not an expert in javaScrit , but i have the following concern. I have the following Script :-
<script type="text/javascript">
$(document).ready(function () {
$("#DCSort").click(function () {
what this indicates is the following :-
1. the script will run when the document finishes loading.
2. when the DCSort DOM element is clicked .
my question is as follow:-
let say that after the document loaded , a new element with DCsort have replaced the old DCSort element , will the original javaScrip fire when the newly added DCSort element has been added using an Ajax call and i use click on it ?
Thanks
Replace this -
$("#DCSort").click(function () {
with this -
$("body")on('click', '#DCSort', function () {
This uses event delegation to account for items added to the DOM after it is originally rendered.
You need event delegation in that case:
Event delegation allows us to attach a single event listener, to a parent element, that will fire for all descendants matching a selector, whether those descendants exist now or are added in the future.
$(document).on('click','#DCSort',function () {
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 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