I have a problem I noticed many times but still haven't understood the real reason.
I have a script that append some .btn buttons by clicking the button #add.
Of course the .btn buttons are to be clicked. So I made an event after the append():
$(".btn").on('click', function(){
alert('clicked');
});
This function works as I want. When I create a button and click on it, it will alert me. But the problem comes when I create more than one button and that I click on one of them. It will pop up an alert for the button I clicked, and for each button with the class that comes after it in the source code.
(As an example, if I create 3 buttons, if I click the first it will alert three times. If I click the second it will alert two times, and if I click the last, it will alert one time.)
I assume that it must be about some Javascript notions I haven't well understood yet. Probably a problem with the class ? I'm a bit lost.
Here is an example if you want to see by yourself : https://jsfiddle.net/nmza0ae4/
Thank you in advance !
Try this : when you add click handler to button user $(".btn").on('click'.. it will add to only available buttons at that point of time.
To add click handler to dynamically added buttons, use below code
$(document).on('click',".btn", function(){
alert('clicked');
});
$('#add').click(function(){
$('html').append('<button class="btn">Test</button>');
$(".btn").on('click', function(){
alert('clicked');
});
});
What you are doing is adding event handler on each click. When new button is added, new event handler is attached to button and hence multiple alert.Put event handler outside the scope
$('#add').click(function(){
$('html').append('<button class="btn">Test</button>');
});
$(document).on('click',".btn", function(){
alert('clicked');
});
You can use $(document).on('click' function ...
$(document).ready(function(){
$('#add').click(function(){
$('html').append('<button class="btn">Test</button>');
});
});
$(document).on('click',".btn", function(){
alert('clicked');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="add">
Add
</button>
As the Add button adds to dom you will need event delegation. Code for adding the button tag looks fine.
$(document).ready(function(){
$('#add').click(function(){
$('html').append('<button class="btn">Test</button>');
});
});
$(document).on("click",'.btn', function(){
alert('clicked');
});
You can unbind the event before binding the event like this.
$('#add').click(function(){
$('html').append('<button class="btn">Test</button>');
$(".btn").off("click");
$(".btn").on("click",function(){
alert('clicked');
})
});
or you can globally write the click event for all the dynamically added button like
$('#add').click(function(){
$('html').append('<button class="btn">Test</button>');
});
$(document).on('click',".btn",function(){
alert('clicked');
});
But the standard way is the 2nd one.
https://jsfiddle.net/Rishi0405/nmza0ae4/2/
try this:
$(document).ready(function(){
$('#add').click(function(){
$('html').append('<button class="btn">Test</button>');
});
$(document).on('click',".btn", function(){
alert('clicked');
});
});
Related
<button class="changeMe"> Click Me </button>
$(".changeMe").on("click", function(){
console.log("I should only work the first time!")
$("changeMe").addClass("secondClass").removeClass("changeMe");
});
$(".secondClass").on("click", function(){
console.log("Now I should Work!")
});
This is basically what my code looks like.
I click the button.
Chrome developer tools show that the class was removed.
I click the button again, and the same bit of jquery code runs even thou the class its pointing too dosnt exist.
How do I stop that from happening.
EDIT:: Ooopss forgot the dot. I have the dot in my solution. This is just for demonstration purposes. Added dot.
1) Add . before class name, so it will be $(".changeMe") and $(".secondClass")
2) Use $(document).on("click") event
Try:
$(document).on("click",".changeMe", function(){
console.log("I should only work the first time!")
$(".changeMe").addClass("secondClass")
$(".changeMe").removeClass("changeMe");
});
$(document).on("click",".secondClass", function(){
console.log("Now I should Work!")
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<button class="changeMe"> Click Me </button>
Try this on clicking .secondClass. You have to bind the events dynamically.
$(document).on("click",".secondClass", function(){
console.log("Now I should Work!")
});
You need to use event delegation because you are changing classes manually. Also . is needed for selecting class names.
Edit : Instead of event delegation, you can use the following, bind the event to the second class, after the class is added.
Use one() for binding to work only once.
$(".changeMe").one("click", function(e){
console.log("I should only work the first time!")
$(".changeMe").addClass("secondClass").removeClass("changeMe");
$(".secondClass").on("click", function(){
console.log("Now I should Work!")
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<button class="changeMe"> Click Me </button>
This code should work
$("body").on("click", '.changeMe', function(){
console.log("I should only work the first time!")
$(".changeMe").addClass("secondClass").removeClass("changeMe");
});
$("body").on("click", '.secondClass', function(){
console.log("Now I should Work!")
});
Try the following:
$(".changeMe").on("click", function(e){
if($(e.target).is('.changeMe')) {
console.log("I should only work the first time!")
$(".changeMe").removeClass("changeMe").addClass("secondClass");
} else {
console.log("Now I should Work!");
}
});
i need to trigger only one click on specific element that can be on page load time or added dynamically in the future. Some code
This code work just fine for elements that are rendered on load time but wont bind the click event to new elements dynamically added
$(".message-actions .accept").one("click", function(e){
console.log("accept");
});
In the other hand if i do it this way, it will bind the event to new elements but don't unbind the event so if i click it again it will print the same console log
$("body").on("click", ".message-actions .accept", function(e){
console.log("decline");
$(this).unbind("click");
});
At last if i do it in this other way it will only fire the event in the first element i click even if there is more than one loaded or added after.
$("body").one("click", ".message-actions .accept", function(e){
console.log("decline");
});
How can i do this?
Thanks
You can add data to the element that remembers whether the handler has run before:
$("body").on("click", ".message-actions .accept", function() {
if (!$(this).data("run-once")) {
console.log("decline");
$(this).data("run-once", true); // Remember that we ran already on this element
}
});
I would do it this way:
var handleClick = function () {
// do your work
alert("decline");
// unbind
$("body").off("click", ".message-actions .accept", handleClick);
};
$("body").on("click", ".message-actions .accept", handleClick);
Check this fiddle
You can solve it like this, if it suits your situation : http://jsfiddle.net/hu4fp5qs/1/
$("body").on("click",".message-actions .accept",function(){
$(this).removeClass("accept").addClass("decline");
alert("Declined");
});
On click remove class accept and add class decline.
This will help you in styling both the cases differently so that you can distinguish between them.
.accept{
background-color:green;
}
.decline{
background-color:red;
}
I use a dialog to get the user input, but I found the user may click double click the button and added the content twice, the cause is the dialog fadeout too slow or the user clicked twice on the mouse.. I don't want to adjust the fadeout speed, instead, how to enable the button only can be clicked once?
jQuery provides the one() method to register a one-shot handler that will only run once.
You can write:
$("#yourButton").one("click", function() {
// Add content...
});
You can disable the button once it was clicked to prevent any further clicks:
$('button').on('click', function() {
$(this).prop('disabled', true);
});
Here is my suggestion. If you are destroying the dialog on exit, just unbind the click event
$('.my-button').on('click', function(){
// process code
$(this).off('click');
});
You can read about off here
And here is a demo. First will not allow other clicks but the second will.
source
Here is a Plunker that shows how you can do this. Pretty much all you need to do is add the following line in your button:
onClick="this.disabled = true;"
So that your button HTML will look something like this:
<button type="submit" onClick="this.disabled = true;">Submit</button>
try this:
$('.myButton').click(function(){
$(this).attr('disabled',true);
....
})
try this with css
$("#yourButton").one("click", function() {
$(this).css('pointer-events', 'none');
})
Upon document load, am trying to trigger the click event of the first radio button.... but the click event is not triggered.Also, tried 'change' instead of click ...but its the same result.
$(document).ready(function() {
//$("#checkbox_div input:radio").click(function() {
$("input:radio:first").prop("checked", true).trigger("click");
//});
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
});
Please follow the below link to the question
Example:
http://jsbin.com/ezesaw/1/edit
Please help me out in getting this right.
Thanks!
You are triggering the event before the event is even bound.
Just move the triggering of the event to after attaching the event.
$(document).ready(function() {
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
Check Fiddle
Switch the order of the code: You're calling the click event before it is attached.
$(document).ready(function() {
$("#checkbox_div input:radio").click(function() {
alert("clicked");
});
$("input:radio:first").prop("checked", true).trigger("click");
});
My solution is a bit different:
$( 'input[name="your_radio_input_name"]:radio:first' ).click();
$("#radio1").attr('checked', true).trigger('click');
In my case i had to load images on radio button click,
I just uses the regular onclick event and it worked for me.
<input type="radio" name="colors" value="{{color.id}}" id="{{color.id}}-option" class="color_radion" onclick="return get_images(this, {{color.id}})">
<script>
function get_images(obj, color){
console.log($("input[type='radio'][name='colors']:checked").val());
}
</script>
lets say I have
function trigger(){
$('a.pep').each(function(){
$('a.pep').click(function(){
console.log($(this).val());
});
});
}
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
trigger(); //now i do but the others have duplicated trigger
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
});
So it seems that the click event is being applied twice/+ because the console.log is lauched more than once by click
How can i prevent this?
The problem is that you call $('a.pep').click() lots of times. (In fact, you bind as many click handlers as there are matching elements to each element. And then you do it again every time one of them is clicked.)
You should lever the DOM event bubbling model to handle this. jQuery helps you with the on method:
$(document.body).on('click', 'a.pep', function() {
console.log('element clicked');
$(document.body).append('<a class="pep">Click handlers handled automatically</a>');
});
See a working jsFiddle.
Note that I have removed the val call, because a elements can't have a value... Note also that the on method is introduced in jQuery 1.7; before that, use delegate:
$(document.body).delegate('a.pep', 'click', function() {
Small change to your trigger function is all you need. Just unbind the click event before binding to ensure that it is never added more than once. Also, you don't need to use each when binding events, it will add the event to each item automatically.
function trigger(){
$('a.pep').unbind('click').click(function() {
console.log($(this).val());
});
}
You can check using data('events') on any element if the required event is attached or not. For example to check if click event is attached or not try this.
if(!$('a.pep').data('events').click){
$('a.pep').click(function(){
console.log($(this).val());
});
}
you should use jQuery live here because you add DOM elements dynamicly and you want them to have the same click behaviour
function push(){
$('body').append('<a class="pep">hey mate i have no trigger yet</a>');
}
$(document).ready(function(){
$('a.push').click(function(){
push();
});
$('a.pep').live('click', function(){
console.log($(this).val());
});
});
Try:
if($('a.pep').data('events').click) {
//do something
}
i think if you use live() event you dont need to make function
$('a.pep').live('click', function(){
console.log($(this).val());
});