8

I've already looked at similar questions but the answers provided involve buttons and not div elements. When I click the div element with id click, the click event handler is disabled by unbind() and sets a timer for 2 seconds. After 2 seconds, the click event handler should be enabled again by bind(). The problem is that the click event handler doesn't seem to get "rebound". I am appending text to another div element to check if the click event handler is active.

Here is my JSFiddle.

Syscall
  • 19,327
  • 10
  • 37
  • 52
user701510
  • 5,563
  • 17
  • 61
  • 86

5 Answers5

15

Another approach to the whole problem is not to bother with unbinding and rebinding and just use a "disabled" flag:

$(document).ready(function(){

   var clickDisabled = false;
   $('#click').click(function(){
      if (clickDisabled)
         return;

      // do your real click processing here

      clickDisabled = true;
      setTimeout(function(){clickDisabled = false;}, 2000);
  });

});
nnnnnn
  • 147,572
  • 30
  • 200
  • 241
0

When you are rebinding the function the second time you are binding just a subset of all your code - all it does it output bound to the status, but it doesn't contain any of the code for doing a timeout a second time.

Also, you will like the .one() function.

I've fixed up your code here: https://jsfiddle.net/eQUne/6/

function bindClick() {
    $('#click').one('click', function() {
        $('#status').append("bound ");
        setTimeout(bindClick, 2000);
    });
}

$(document).ready(function(){
    bindClick();
});
Syscall
  • 19,327
  • 10
  • 37
  • 52
Ariel
  • 25,995
  • 5
  • 59
  • 69
0

Try this:

$(document).ready(function(){

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

    $('#click').unbind('click');
    $('#status').append("unbound ");

    setTimeout(
        function(){
            $('#click').bind('click',function(){

            });
            $('#status').append("bound ");           
        },
        2000
        );
    });
});

You misspelled setTimeout and your "bound" message was being appended only on click.

Ryan Doherty
  • 38,580
  • 4
  • 56
  • 63
0

If I got what you were asking correctly, this should work:

<div id="click" >time out</div>
<div id="status"></div>

$(document).ready(function() {
    $('#click').click(unbindme);

    $('#status').html('bound'); 

    function unbindme()
    {
        $('#click').unbind('click');
        $('#status').html('unbound');
    
        setTimeout(function(){
            alert('here');
            $('#status').html('bound'); 
            $('#click').click(unbindme);   
        }, 2000);
    }
}

Check it out here: https://jsfiddle.net/eQUne/

Syscall
  • 19,327
  • 10
  • 37
  • 52
JesseBuesking
  • 6,496
  • 4
  • 44
  • 89
0

I answer your question but just don't kill yourself :)) Just kidding... Your code is fine just a typo: setTimeOut should be setTimeout (the O should be o)

Alireza Noori
  • 14,961
  • 30
  • 95
  • 179