Trigger events from classes assigned afterwards [duplicate] - javascript

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?

Related

Create link from jquery [duplicate]

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>

jQuery: .click doesn't work on appended div [duplicate]

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);
});

JQuery .on method not responding [duplicate]

This question already has answers here:
jQuery .on() method doesn't see new elements
(5 answers)
Closed 8 years ago.
I am using Jquery 2.1.0. I have injected some elements to the DOM (containing label) into a div element. I am using the following JavaScript to handle click event on all labels but it is completely dead and not responding. I checked and Jquery is loaded.
$('label').on("click", function () {
var ul = $(this).parent().children("ul:first");
if (ul.is(':visible')) {
ul.css({ "display": "none" });
}
else {
ul.css({ "display": "block" });
}
});
I used developer tools in IE 10 and debugged the code. When I hit F5 it goes to my break point (on first line of my code) but when I click a label nothing happens and no errors.
This will only assign the event handler to label elements which exist initially on the page:
$('label').on("click", function () {
// ...
});
To catch elements which are added later, you need to assign the event handler to a common parent element (which isn't added/removed during the life of the page) and filter the source elements, like this:
$(document).on('click', 'label', function () {
// ...
});
Note that there are two selectors:
document
'label'
The first, which is the target of the event handler, is only evaluated once when the page loads (or when this line of code is evaluated, which is generally when the page loads). This attaches the handler to the document object. Since all events "bubble up" to parent elements, this will catch all click events on the page (unless propagation is explicitly stopped, of course).
The second, which is the "filter" for the .on() method's handler, is evaluated any time an event is caught by this handler. It filters out the elements which originated the click event so that the handler is executed only for those which match the filter.
I've actually recently blogged about this very subject.
You need to use event delegation since your label has been dynamically created element:
Event delegation allows us to attach a single event listener, to a
parent element, that will fire for all children matching a selector,
whether those children exist now or are added in the future.
$('body').on('click','label', function() {
// Your code here
});
Basically, event delegation will helps you to attach click event to newly added label elements in your case
you should use event delegation for that
$(document).on("click","label",function(){
});
Event delegation allows you to attach a single event listener, to a parent element, that will fire for all children matching a selector, whether those children exist now or are added in the future.
From this answer to another question here: https://stackoverflow.com/a/8337382/2407870
It seems that the method doesn't work for some inline elements in Chrome. If your element is inline, try changing the display to block.

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

Categories