I have multiple classes on a page of the same name. I then have a .click() event in my JS. What I want to happen is the click event only happen once, regardless of multiple classes on my page.
The scenario is that I am using AJAX to add to cart. Sometimes on the home page there might be a featured product and a top offer which means that the same class .add .#productid# is there and when clicked the add to cart AJAX is fired twice.
I thought about making 'click areas' so I would have .container-name .add .#pid# therefore giving unique clicks.
Is this the only solution?
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
<div class="addproduct 151">product info</div>
$(".addproduct").click(function(){//do something fired 5 times});
Try making use of the
.off()
handler:I attach a click event handler on an OK modal button to act on
click
event of the object with class.archive-link
.On the first click, the event fires only on that
.archive-link
object that I asked the function to act on (var linkObj
). But when I click the same link the second time and hit OK on the modal, the event fires on every object that has.archive-link
that I clicked before.I used the solutions above but unfortunately did not work. It was when I called .off() within the modal OK button click function that the propagation stopped. I hope this helps.
Just do below code it's working absolute fine
This should fix it and should be a good habit: .unbind()
I solved it by using inline jquery function call like
Simply enter code hereIn JQuery, ones event is triggered you just check number of occurrences of classes in file and use for loop for next logic. for identify number of occurrences of any class, tag or any DOM element through JQuery : var len = $(".addproduct").length;
In this situation I would try:
then, if you need to perform something in the other elements with the same class on click on one ot them you can loop through the elements: