jQuery click not working for dynamically created items
Do this:
$( '#wrapper' ).on( 'click', 'a', function () { ... });
where #wrapper
is a static element in which you add the dynamic links.
So, you have a wrapper which is hard-coded into the HTML source code:
<div id="wrapper"></div>
and you fill it with dynamic content. The idea is to delegate the events to that wrapper, instead of binding handlers directly on the dynamic elements.
Btw, I recommend Backbone.js - it gives structure to this process:
var YourThing = Backbone.View.extend({
// the static wrapper (the root for event delegation)
el: $( '#wrapper' ),
// event bindings are defined here
events: {
'click a': 'anchorClicked'
},
// your DOM event handlers
anchorClicked: function () {
// handle click event
}
});
new YourThing; // initializing your thing
Click event doesn't work on dynamically generated elements
The click()
binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future. To do that, you'll have to create a "delegated" binding by using on()
.
Delegated events have the advantage that they can process events from descendant elements that are added to the document at a later time.
Source
Here's what you're looking for:
var counter = 0;
$("button").click(function() { $("h2").append("<p class='test'>click me " + (++counter) + "</p>")});
// With on():
$("h2").on("click", "p.test", function(){ alert($(this).text());});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script><h2></h2><button>generate new element</button>
jQuery onClick not working on dynamically added elements
You need to event Delegation on your dynamically added element so that a click event can be listened.
Since the element added after the
DOM
is ready are not part ofDOM
we need to useevent Delegation
so that a click event can be triggered from those elements.
Demo:
$(document).ready(function() {
//display pic real time and add new upload button
$(document).on("change", "input[type='file']", function(e) {
if (e.target.files[0] != null) {
if (this.files && this.files[0]) {
var reader = new FileReader();
reader.onload = function(e) {
$("#miniImgHolder").after("<div class='col-1 miniImg'><img class='img-fluid' src='" + e.target.result + "'></div>"); //.miniImg on click not works if it set from here
}
reader.readAsDataURL(this.files[0]);
}
}
});
//click not working for bellow code
$(document).on("click", '.miniImg', function() {
console.log("i am not working on newly added miniImg");
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="col-1" id="miniImgHolder">
<input type="file" name="my_file[]" class="custom-file-input custom-file-label theFiles" style="cursor:pointer;">
</div>
<div class="col-1 miniImg">
<img class="img-fluid" style="width:75px; height:75px;" src="~/Images/img1.png">
<!--this .miniImg on click works fine-->
</div>
<div class="col-1 miniImg">
<img class="img-fluid" style="width:75px; height:75px;" src="~/Images/img2.png">
<!--this .miniImg on click works fine-->
</div>
Jquery click event not firing on the element created dynamically using jquery
Use even delegation instead
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.
More info
$(document).on('click', '.remove', function () {.....
jquery - Click event not working for dynamically created button
You create buttons dynamically because of that you need to call them with .live()
method if you use jquery 1.7
but this method is deprecated (you can see the list of all deprecated method here) in newer version. if you want to use jquery 1.10 or above you need to call your buttons in this way:
$(document).on('click', 'selector', function(){
// Your Code
});
For Example
If your html is something like this
<div id="btn-list">
<div class="btn12">MyButton</div>
</div>
You can write your jquery like this
$(document).on('click', '#btn-list .btn12', function(){
// Your Code
});
Jquery click function is not working for dynamic elements
The click()
function you can call on the elements which have direct binding. Direct binding will only attach event handler which are present at the time of DOM loading i.e. static elements.
If there are elements created after DOM is loaded, then not all the events associated with them would be triggered if you have not attached the event handlers correctly.
And when you create dynamic elements that means they are being created after DOM is loaded and they were not present at the time of direct binding, so you can not call directly click()
on that.
if you want to get click
functionality on dynamic created elements, you'll have create a delegated binding by using on. This you can achieve by adding a .on
handler to a static parent element.
Delegated events have the advantage that they can process events from descendant elements that
are added to the document at a later time.
Change this line
$("#questlist_item_button_reward" + obj.questid).click(function() {
alert("reward");
});
to
$("#call_questitem").on("click", "#questlist_item_button_reward" + obj.questid, function() {
alert("reward");
});
And do the same for the go
button as well.
DEMO
dynamically created li click event not working jquery
Just put your code inside ready function and it will work with your second attempt that using event delegation on(), check snippet bellow.
Hope this helps.
Snippet
$(function(){ var groups = ['test-1','test-2','test-3']; var len = groups.length; for (var i = 0; i < len; i++) { var id = groups[i].split("-")[0]; var name = groups[i].split("-")[1]; $('#listbox-groups').append('<li id="' + id + '" class="listbox-li"><a href="#" class="listbox-li-a" style="text-decoration: none">' + name + '</a></li>'); }
$(document).on("click", "#listbox-groups li", function(event) { alert($(this).text()+" clicked"); });});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><ul id="listbox-groups"></ul>
Ajax JQuery: On click for dynamically created elements not working
you just need to use $(this) so you can determine which .like class you have clicked. example below
$(".content").on("click",".like",function(){
var id = $(this).attr("id"); // get value of id
alert(id); // alert value
$(this).css("color","red"); // change color
});
onclick is not working for dynamically added buttons
Thanks everyone by giving great ideas and I got solution for by question by just making an simple change in my code.
function details(){
$('subSection').html('');
$('.subSection').append('<section><button type="button" class="btn btn-danger hideEquipmentDetails" onclick="clickme()"><i class="fa fa-
times" ></i></button>
</section>')
var details= response.data.filters;
$.each(details,function(i,value){
$('.subSection').append('<section><label>Speed</label><label>'+value.speed+'</label></section>');
});
}
Just append the button first then append the data.
Click event is not working for dynamically added button
When you inject code into the DOM, the jQuery event handlers are not attached/bound to the new elements. (jQuery already did the bindings to DOM elements before the new code was injected). Therefore, when you click a button, no jQuery click event is trapped.
To attach event handlers (and thereby grab events from) injected elements, you must use jQuery .on()
, as follows:
jsFiddle Demo
$(".statiscDIV").append('<div>FIRST</div>');
$(".statiscDIV").append('<div>hello <button class="MakeHoldDetailLinkButton">View</button> </div>');
$(document).on('click','.MakeHoldDetailLinkButton',function(){
showMakeAndHold();
});
function showMakeAndHold() {
alert("HIIIIIII");
}
The .on()
method was added in jQuery 1.7 to replace bind()
, .delegate()
, and .live()
-- it does the same thing as all of these. (To unbind event handlers from ANY DOM elements, use .off()
)
Source: http://api.jquery.com/on/
Related Topics
Appending HTML String to the Dom
Jquery Load() Only Working in Firefox
Google Maps API V3: How to Remove All Markers
Get Pixel Color from Canvas, on Mousemove
Jquery/JavaScript Collision Detection
Why Is the Value of My Input Always Empty If I Store It in a Variable
How to Run a Function When the Page Is Loaded
Resize Html5 Canvas to Fit Window
Html Form Readonly Select Tag/Input
Why Does Canvas.Todataurl() Throw a Security Exception
Jquery Disable/Enable Submit Button
How to Get the Entire Document HTML as a String
Browser Detection Versus Feature Detection
Way to Ng-Repeat Defined Number of Times Instead of Repeating Over Array
Link Index.Html Client.Js and Server.Js
Execute PHP Function With Onclick
Determine Timezone from Latitude/Longitude Without Using Web Services Like Geonames.Org
Using Html5/Canvas/JavaScript to Take In-Browser Screenshots