Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

jquery

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}); 
like image 912
izip Avatar asked Apr 06 '11 08:04

izip


2 Answers

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/

like image 132
Ivan Kalafatić Avatar answered Sep 21 '22 13:09

Ivan Kalafatić


$(document).on('click', '.addproduct', function () {     // your function here }); 
like image 22
Entara Avatar answered Sep 19 '22 13:09

Entara