izip
izip

Reputation: 2096

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

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

Upvotes: 108

Views: 773806

Answers (21)

Ivan Kalafatić
Ivan Kalafatić

Reputation: 1748

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/

Upvotes: 158

Sasindu Bandara
Sasindu Bandara

Reputation: 41

This is the only answer for this.

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

Upvotes: 0

CHANDAN KUMAR
CHANDAN KUMAR

Reputation: 21

class name denoted by dot(.) and click method will trigger when you will click on where you given class name addproduct.

$(".addproduct").click(function(){
  //your logic on click
  console.log("clicked");
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<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>

Upvotes: 2

embulldogs99
embulldogs99

Reputation: 980

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

}

Upvotes: 0

Farouk ElKhabbaz
Farouk ElKhabbaz

Reputation: 131

$(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>

Upvotes: 4

Figure Out
Figure Out

Reputation: 11

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>

Upvotes: 1

Girish Ninama
Girish Ninama

Reputation: 593

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

}

Upvotes: 2

hatemjapo
hatemjapo

Reputation: 840

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.

Upvotes: 1

Kristianne Nerona
Kristianne Nerona

Reputation: 745

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.

Upvotes: 1

Paolo Anghileri
Paolo Anghileri

Reputation: 457

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

Upvotes: 17

virendra gawale
virendra gawale

Reputation: 21

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++){
          ...
        }
 });

Upvotes: 2

Entara
Entara

Reputation: 1360

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

Upvotes: 110

SteveGSD
SteveGSD

Reputation: 1750

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

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

Upvotes: 8

Brain
Brain

Reputation: 440

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 "contact".

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.

Upvotes: 1

SreBalaji Thirumalai
SreBalaji Thirumalai

Reputation: 223

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

Upvotes: -4

Ravi
Ravi

Reputation: 163

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>

Upvotes: 6

Lesenus
Lesenus

Reputation: 51

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.

Upvotes: 5

Francisco Dal Cortivo
Francisco Dal Cortivo

Reputation: 31

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

Upvotes: 2

Max7K
Max7K

Reputation: 151

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

Upvotes: 11

EMMERICH
EMMERICH

Reputation: 3474

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.

Upvotes: 50

Headshota
Headshota

Reputation: 21449

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.

Upvotes: 28

Related Questions