Mike Van Stan
Mike Van Stan

Reputation: 396

Why is this function firing three times?

I have a code snippet to track the clicks of an add to cart button three times.

It's inside a pop up 'quick view' modal if you are confused why I've written it this way.

To be precise - this part is firing three times on every click:

$(".qlBtns").one("click", function() {

  mboxDefine('dynamicElement5', 'QuickViewAddToCartClicked');
  mboxUpdate('QuickViewAddToCartClicked', 'Clicked=Yess');

});

Complete snippet below:

$(document).ready(function() {
  $(".quickview_btn").click(function() {

    var quickview_url = $(this).attr("href");
    var qvURL = $(this).attr("href");

    $(".quickview_btn").colorbox({
      href: qvURL,
      opacity: 0.6,
      onComplete: function() {

        $(".qlBtns").one("click", function() {
          mboxDefine('dynamicElement5', 'QuickViewAddToCartClicked');
          mboxUpdate('QuickViewAddToCartClicked', 'Clicked=Yess');
        });

      }
    });

    mboxDefine('dynamicElement', 'QuickViewPLPclicked');
    mboxUpdate('QuickViewPLPclicked', 'paramURL=' + quickview_url);
  });
});

Upvotes: 0

Views: 82

Answers (1)

Deep
Deep

Reputation: 9804

you should bind the event

$(".qlBtns").on("click", function() {});

only once to get it triggered a single time, since you are binding the event inside the another function oncomplete callback , it is possible that the event is getting binded more than once. You should do this binding outside the .colorbox function. in case you can not do this i will suggest you to unbind and bind the event by using below code.

$(".qlBtns").off("click").on("click", function() {});

Upvotes: 1

Related Questions