This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
jQuery click event not working after adding class
(7 answers)
Closed 5 years ago.
I am trying to change the functionality of a button by changing its ID dynamically.
<srcipt>
$("#old-id").click(function func_P(){
//Some code
this.id = "new-id";
});
$("#new-id").click(function func_Q(){
// some other code
});
$("#clear").click(function func_R(){
$(".in").attr("id","new-id");
});
</script>
<body>
<button id="old-id" class="in">Button A</button>
<button id="clear">Clear</button>
</body>
But the problem I am facing is that when I click "Button A" the id gets changed but when I click "Button A" again func_P() is executed again instead I intend to call func_Q.
Use .on function to bind (live) click.
$("#old-id").on('click', function func_P(e) {
//Some code
if (this.id == "old-id") {
this.id = "new-id";
console.log('old id clicked');
e.stopPropagation()
}
});
$(document).on('click', "#new-id", function func_Q() {
// some other code
console.log('new id clicked');
});
$("#clear").on('click', function func_R() {
$(".in").attr("id", "old-id");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="old-id" class="in">Button A</button>
<button id="clear">Clear</button>
And if you want to clear id, you should change:
$(".in").attr("id","new-id");
To:
$(".in").attr("id", "old-id");
Related
This question already has answers here:
Direct vs. Delegated - jQuery .on()
(6 answers)
Closed 4 years ago.
I'm trying to add a data-name attribute on clicking one element and then when that element is clicked do something else.
$(".btn01").on("click", function() {
$(".next").attr("data-name", "btn02");
});
$("[data-name='btn02']").on("click", function() {
console.log("I clicked this button");
});
It is updating in the DOM but not working?
Any ideas?
You must use event delegation since the attribute you're using in the selector of the second click event [data-name='btn02'] is created dynamically by the JS code:
$(".btn01").on("click", function() {
$(".next").attr("data-name", "btn02");
});
$("body").on("click", "[data-name='btn02']", function() {
console.log("I clicked this button");
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button type="button" class="btn01">CLICK ME then click the span bellow</button>
<br><br>
<span class="next">Next span</span>
Try the following, use event delegation for attaching event to "[data-name='btn02']", as $("[data-name='btn02']") element will not exist till $(".btn01") is clicked.
$(".btn01").on("click", function() {
$(".next").attr("data-name", "btn02");
});
$(document).on("click", "[data-name='btn02']", function() {
console.log("I clicked this button");
});
If you are just trying to make it so the first button needs to be clicked before the second can, you can just use a boolean variable for that:
var firstButtonClicked = false;
$(".btn01").on("click", function() {
firstButtonClicked = true;
});
// the second button
$(".next").on("click", function() {
if (firstButtonClicked == true) {
console.log("I clicked this button after the first one");
}
});
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I am trying to create a simple list with the option to add and remove elements, but it seems there are some scope rules about the selectors that I couldn't find in the official documentation. My HTML, including the jQuery is as follows:
$(function() {
$("#add").click(function() {
let val = $("input").val();
if (val !== "") {
let ele = $("<li></li>").text(val);
ele.append("<button class='rem'>X</button>");
$("#mylist").append(ele);
$("input").val("");
// $(".rem").click(function(){
// $(this).parent().remove();
// });
};
});
$(".rem").click(function() {
$(this).parent().remove();
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" placeholder="Add new item">
<button id="add">Add</button>
<ol id="mylist">
</ol>
The commented part is the part that is running properly, but the one that is outside of the click function for the #add element is not working.
When you call $(".rem").click(.. jQuery will look for elements with class ".rem" and bind this new click event.
However, this only happens once. If you add elements later with the same class, those don't automatically get that event.
So what you'll want to do is bind this event to the new element you created, after you created it.
Lets clean this up:
<script>
function onAddClick() {
let val = $("input").val();
if (val !== ""){
let ele = $("<li></li>").text(val);
ele.click(onRemClick); <--- HERE
ele.append("<button class='rem'>X</button>");
$("#mylist").append(ele);
$("input").val("");
};
}
function onRemClick() {
$(this).parent().remove();
}
$(function() {
$("#add").click(onAddClick);
});
</script>
This question already has answers here:
Event binding on dynamically created elements?
(23 answers)
Closed 5 years ago.
I'm trying to use a button that is printed by .html(). I've tried .find() after searching through this site but the onclick event still seem not detected.
<div id = "div4html">div</div>
<button id="printbtn">printbtn</button>
<script>
$("#printbtn").on( "click", function() {
$("#div4html").html('<button id ="btntest">btntest</button>');
});
$("#div4html").find("#btntest").on( "click", function() {
alert("on click");
});
</script>
while the #btntest onclick doesn't show an alert, the CSS on #btntest works.
There is something I don't know about elements that are created dynamically?
You can't do this because js don't even for events in newly created content by default.
Here is the way to do it :
$("#div4html").on('click', "#btntest" , function() {
// Your code
}
You need to do:-$("#div4html").on( "click", "#btntest", function() {
It's called:- Event Delegation
Example:-
$("#printbtn").on( "click", function() {
$("#div4html").html('<button id ="btntest">btntest</button>');
});
$("#div4html").on( "click","#btntest", function() {
alert("on click");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id = "div4html">div</div><br>
<button id="printbtn">printbtn</button>
Delegate the event from the body
$("body").on( "click",'#btntest', function() {
alert("on click");
});
This question already has answers here:
Event handler not working on dynamic content [duplicate]
(2 answers)
Closed 7 years ago.
I used the following codes to create a "New button" next to the "button". But, when I click the "New button", it cannot create another "New button". Why? I have defined the "click" event of "button" tag
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2jquery.min.js"></script>
<script>
$(document).ready(function() {
$("button").click(function() {
$("body").append("<button type=button>New button</button>");
})
})
</script>
</head>
<body>
<button type="button">button</button>
</body>
Use event delegation for binding events automatically on dynamically added elements.
$(document).ready(function() {
var button = "<button type=button>New button</button>";
$(document).on('click', "button", function() {
$("body").append(button);
});
});
$(document).on('click', "button", function() {
$("body").append("<button type=button>New button</button>");
})
This question already has answers here:
Events triggered by dynamically generated element are not captured by event handler
(5 answers)
Closed 9 years ago.
My JQuery Code is:
$(document).ready(function() {
$('#btnGenSpan').on('click', function(e) {
$("#div_container").html($("#div_container").html()+
"<span>Item-01 <a href='?delete=1' class='delete_item'>X</a></span><br />");
});
$('a.delete_item').on('click',function(e) {
alert('delete clicked');
return false;
});
});
Here is html content:
<input type="button" id="btnGenSpan" value="Generate More Item" /><br /><br />
<div id="div_container">
<span>Default Item-01 <a href='?delete=111' class='delete_item'>X</a></span><br />
<span>Default Item-02 <a href='?delete=112' class='delete_item'>X</a></span><br />
</div>
Here is the JSFiddle here
For static items(Default Item-01 & Default Item-02) X anchor works fine and called delete_item but for those span which are generated by jquery(same html class & anchor generated as default) not called. any help is highly appreciated.
You may want to try using event delegation syntax of on to have the event available for the dynamically created elements. Reason being your original event is bound only to the a.delete_item that already existed in DOM at the time of event binding, so newly added ones just did n't have that event bound to it. So bind the event to the parent container that exists in DOM as long as you need the event so that it gets delegated to the selector (jquery uses event bubbling to make this work) when that event happens.
$('#div_container').on('click','a.delete_item', function(e) {
e.preventDefault();
alert('delete clicked');
});
Demo
You must creat event for new DOM
Try this
$(document).ready(function() {
$('#btnGenSpan').on('click', function(e) {
$("#div_container").html($("#div_container").html()+"<span>Item-01 <a href='?delete=1' class='delete_item'>X</a</span><br />");
$('a.delete_item').on('click',function(e) {
alert('delete clicked');
return false;
});
});
$('a.delete_item').on('click',function(e) {
alert('delete clicked');
return false;
});
});