jQuery $(".class").click(); - multiple elements, click event once

Jquery

Jquery Problem Overview


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

Jquery Solutions


Solution 1 - Jquery

Apologies for bumping this old thread. I had the same problem right now, and I wanted to share my solution.

$(".yourButtonClass").on('click', function(event){
    event.stopPropagation();
    event.stopImmediatePropagation();
    //(... rest of your JS code)
});

event.StopPropagation and event.StopImmediatePropagation() should do the trick.

Having a .class selector for Event handler will result in bubbling of click event (sometimes to Parent element, sometimes to Children elements in DOM).

event.StopPropagation() method ensures that event doesn't bubble to Parent elements, while event.StopImmediatePropagation()method ensures that event doesn't bubble to Children elements of desired class selector.

Sources: https://api.jquery.com/event.stoppropagation/ https://api.jquery.com/event.stopimmediatepropagation/

Solution 2 - Jquery

$(document).on('click', '.addproduct', function () {
    // your function here
});

Solution 3 - Jquery

Could we see your click handler? You're attaching 5 listeners to 5 different elements. However, when the user clicks on the element, only one event is fired.

$(".addproduct").click(function(){
  // Holds the product ID of the clicked element
  var productId = $(this).attr('class').replace('addproduct ', '');

  addToCart(productId);
});

If this solution doesn't work I'd like to look at your click handler.

Solution 4 - Jquery

when you click div with addproduct class one event is fired for that particular element, not five. you're doing something wrong in you code if event is fired 5 times.

Solution 5 - Jquery

In this situation I would try:

$(document).on('click','.addproduct', function(){

    //your code here
   
 });

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:

$(document).on('click','.addproduct', function(){
   $('.addproduct').each( function(){
      
      //your code here
     }
  );
 }
);

Solution 6 - Jquery

I think you add click event five times. Try to count how many times you do this.

console.log('add click event')
$(".addproduct").click(function(){ });

Solution 7 - Jquery

This should fix it and should be a good habit: .unbind()

$(".addproduct").unbind().click(function(){
   //do something 
});

Solution 8 - Jquery

I solved it by using inline jquery function call like

<input type="text" name="testfield" onClick="return testFunction(this)" /> 

<script>
  function testFunction(current){
     // your code go here
  }
</script>

Solution 9 - Jquery

I just had the same problem. In my case PHP code generated few times the same jQuery code and that was the multiple trigger.

<a href="#popraw" class="report" rel="884(PHP MULTIPLE GENERATER NUMBERS)">Popraw / Zgłoś</a>

(PHP MULTIPLE GENERATER NUMBERS generated also the same code multiple times)

<script type="text/javascript">
$('.report').click(function(){...});
</script>

My solution was to separate script in another php file and load that file ONE TIME.

Solution 10 - Jquery

$(document).ready(function(){

    $(".addproduct").each(function(){
          $(this).unbind().click(function(){
               console.log('div is clicked, my content => ' + $(this).html());
           });
     });
}); 
 

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="addproduct 151">product info 1</div>
<div class="addproduct 151">product info 2</div>
<div class="addproduct 151">product info 3</div>
<div class="addproduct 151">product info 4</div>
<div class="addproduct 151">product info 5</div>

Solution 11 - Jquery

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;

 $(".addproduct").click(function(){
       var len = $(".addproduct").length; 
       for(var i=0;i<len;i++){
          ...
        }
 });

Solution 12 - Jquery

Just do below code it's working absolute fine

$(".addproduct").on('click', function(event){
    event.stopPropagation();
    event.stopImmediatePropagation();
    getRecord();
});


function getRecord(){
   $(".addproduct").each(function () {
       console.log("test");
       });
  
}

Solution 13 - Jquery

I had the same problem. The cause was that I had the same jquery several times. He was placed in a loop.

$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});
$ (". AddProduct"). click (function () {});

For this reason was firing multiple times

Solution 14 - Jquery

I tried it myself in my project.

All my rows in a table have a class "contact":

All my rows in a table have a class

My code looks like this:

var contactManager = {};

contactManager.showEditTools = function(row) {
  console.debug(row);
}

$('.contact').click(function(event){
  console.log("this should appear just once!");
  alert("I hope this will appear just once!");
  contactManager.showEditTools(event);
});

And I was first scared to see my whole rows as a result in the Firebug console when I executed the code:

Firebug console screenshot after code execution

But then I realized that the click event was not fired, because no alert-dialog appeared. Firebug shows you just the elements which are affected by the click overiding. So there is nothing to worry.

Solution 15 - Jquery

Try making use of the .off() handler:

$(function () {
    $(".archive-link").click(function (e) {
        var linkObj = $(this);
        var cb = $("#confirm-modal");
        cb.find(".modal-body").append("<p>Warning message.</p>");
        cb.modal('show'); 
        cb.find(".confirm-yes").click(function () {
            $(this).off(); //detach this event
            //ajax call yada yada..
        }

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.

Solution 16 - Jquery

This question have been resolved and also got a lot of responses, but i want to add something to it. I was trying to figure out, why my click element his firing 77 times, and not one time.

in my code, i had an each, running a json response and displaying it as divs with buttons. And then i declared the click event inside the each.

$(data).each(function(){
    button = $('<button>');
    button.addClass('test-button');
    button.appendTo("body");

    $('.test-button').click(function(){
        console.log('i was clicked');
    })
})

If you write your your code like this, the class .test-button will get multiple click events. For example, my data has 77 lines, so the each will run 77 times, that means i will decline the click event on the class 77 times. When you click the element, it will be fired 77 times.

But if you wirte it like this:

$(data).each(function(){
    button = $('<button>');
    button.addClass('test-button');
    button.appendTo("body");
})

    $('.test-button').click(function(){
        console.log('i was clicked');
    })

you are declaring the click element after the each. That means, the each will run its 77 times, and the click element will be declared only one time. So, if you click the element, it will be fired only one time.

Solution 17 - Jquery

Hi sorry for bump this post just face this problem and i would like to show my case.

My code look like this.

<button onClick="product.delete('1')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('2')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('3')" class="btn btn-danger">Delete</button>
<button onClick="product.delete('4')" class="btn btn-danger">Delete</button>

Javascript code

<script>
 var product = {
     //  Define your function
     'add':(product_id)=>{
          //  Do some thing here
     },

     'delete':(product_id)=>{
         //  Do some thig here
     }
 }
</script>

Solution 18 - Jquery

I have found, when I am creating multiple duplicate elements with javascript and inject them into the HTML on page load, Jquery .click() does not work.

In this case, attach an onClick tag to the html element when you generate the element in javascript

$("#items").html('<button onClick="delete_item(`'+item+'`)" value="'+item+'">Remove</button>');

Then later, when you click this button, it will execute the delete_item() function and pass this into it for use later.

function delete_item(item){

    console.log(item);

}

Solution 19 - Jquery

your event is triggered only once... so this code may work try this

    $(".addproduct,.addproduct,.addproduct,.addproduct,.addproduct").click(function(){//do     something fired 5 times});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionizipView Question on Stackoverflow
Solution 1 - JqueryIvan KalafatićView Answer on Stackoverflow
Solution 2 - JqueryEntaraView Answer on Stackoverflow
Solution 3 - JqueryEMMERICHView Answer on Stackoverflow
Solution 4 - JqueryHeadshotaView Answer on Stackoverflow
Solution 5 - JqueryPaolo AnghileriView Answer on Stackoverflow
Solution 6 - JqueryMax7KView Answer on Stackoverflow
Solution 7 - JquerySteveGSDView Answer on Stackoverflow
Solution 8 - JqueryRaviView Answer on Stackoverflow
Solution 9 - JqueryLesenusView Answer on Stackoverflow
Solution 10 - JqueryFarouk ElKhabbazView Answer on Stackoverflow
Solution 11 - Jqueryvirendra gawaleView Answer on Stackoverflow
Solution 12 - JqueryGirish NinamaView Answer on Stackoverflow
Solution 13 - JqueryFrancisco Dal CortivoView Answer on Stackoverflow
Solution 14 - JqueryBrainView Answer on Stackoverflow
Solution 15 - JqueryKristianne NeronaView Answer on Stackoverflow
Solution 16 - JqueryhatemjapoView Answer on Stackoverflow
Solution 17 - JqueryFigure OutView Answer on Stackoverflow
Solution 18 - Jqueryembulldogs99View Answer on Stackoverflow
Solution 19 - JquerySreBalaji ThirumalaiView Answer on Stackoverflow