5

I have been dealing with an odd problem that .click() events happen twice whenever placed in a jQuery Dialog.

My simple test case is below and a live example is here

  <div id="popup" style="display: none">
    <a href="javascript:void(0);" id="testlink">Test Link</a>
    <script type="text/javascript">
      $('#testlink').click(function(){
        alert("Test Link clicked");
        return 0;
      });
    </script>
  </div>
  <script type="text/javascript">
  $(document).ready(function(){
    $('#popup').css('display','block');
    var h=($(window).height()+0.0)*0.9;
    var w=($(window).width()+0.0)*0.9;
    if(w >= 800){
      w = 800;
    }
    $('#popup').dialog({
      autoOpen: true,
      width: w,
      height: h,
      modal: true,
      open: function(event,ui){
        $('body').css('overflow', 'hidden');
      },
      close: function(event,ui){
        $('body').css('overflow', 'scroll');
      }
    });
  });
  </script>

2 Answers 2

7

Move the <script> block that registers the click event outside of the popup div, I think the JS gets parsed another time when the div becomes visible...

Sign up to request clarification or add additional context in comments.

1 Comment

Huh. I didn't get the double call running locally with your slim sample, but I did get it on your live sample running on your machine. Your sample site has some extra stuff going on too.
2

The most common reason, why this happens, is that your script is parsed 2 times. If you are not sure, where this happens or have no time to debug, here's a simple workaround.

The idea is to remove all active hadlers, before a new hadler is applied.

$( '.selector' ).unbind( 'click' ).click( function() {
    // your code
});

If you use jQuery 1.7 or above, you can use the following syntax.

$( '.selector' ).off( 'click' ).on( 'click', function() {
    // your code
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.