Sam
Sam

Reputation: 1511

jQuery - Trigger Click Inside a Fancybox

I have a page that will popup a fancybox using

$('#showpopup').fancybox().trigger('click');

This may be triggered to popup several times (not at once) as the user navigates the page.

On the popup there is a button which triggers an action when clicked

$('#mybutton').click(function(){

   $('#otherbutton').trigger('click');

});

When the fancybox popup shows first time I click #mybutton and #otherbutton will trigger once.

When the fancybox popup shows the second time I click #mybutton and #otherbutton will trigger twice.

When the fancybox popup shows the third time I click #mybutton and #otherbutton will trigger three times...and so on.

How can I stop this issue with fancybox so that otherbutton will only trigger once?

Upvotes: 1

Views: 2222

Answers (1)

Jasper
Jasper

Reputation: 76003

It sounds like you are binding the click event handler for the #mybutton element within a Fancybox event (onStart, onComplete, etc.).

Two ways to fix this are:

  1. On the onClosed or onCleanup events you can unbind the click event handler for the #mybutton element: $('#mybutton').unbind('click');. This way they will not build up and fire multiple times on a single click.
  2. You can move $('#mybutton').click(function(){$('#otherbutton').trigger('click');}); outside any Fancybox event handler (if the button is not present in the DOM until the Fancybox is displayed then you can use .delegate() to bind the click event handler to this button). $(document).delegate('#mybutton', 'click', function () {...}) (note that you can change document to any root element that is present in the DOM at the time of binding).

Docs:

I also noticed that you linked to the old version of Fancybox, if you are using 1.x then I suggest changing to 2.0: http://fancyapps.com/fancybox/

Upvotes: 2

Related Questions