0

I have a function that is triggered by a click. I want after I click it, disabling the click. So I made this

$('.item-blog').on('click', function(){

    $('.item-blog').off('click');

});

and It's working perfectly.

But later on, at the end of all the events, within the last function, when I have resetted all the stuff and I have run all the code, I want to be able to re click the first function in order to fire the same events again. So I put this within the last function that resets everything.

$('.item-blog').on('click');

But it is not working at all.

I even tried bind and unbind but every time I want to re enable the click, it is never working.

Some help?

Thank you very much

rolfo85
  • 717
  • 3
  • 11
  • 27
  • 1
    The `.off()` method doesn't turn the handler off in the sense of turning off a light switch, it *removes* the handler in the sense of pulling out the lightbulb and all of its associated wiring. – nnnnnn Mar 29 '17 at 01:29
  • http://stackoverflow.com/questions/2459153/alternative-to-jquerys-toggle-method-that-supports-eventdata – dippas Mar 29 '17 at 01:32
  • Here's another duplicate with an answer that uses a flag rather than adding and removing the handler: http://stackoverflow.com/questions/38906793/event-click-on-and-off – nnnnnn Mar 29 '17 at 01:35

2 Answers2

1

You can try the on and off as below to toggle the click.

$(document).ready(function(){

function toggleClick(on) {

   if(on) {
      $('.item-blog').on('click', function(){
         console.log('clicked');
         toggleClick(false);

      });

   } else {
      $('.item-blog').off('click');
   }

}

toggleClick(true);

$('.item-blog-reset').on('click', function(){
    console.log('Reset done');
    toggleClick(true);

});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="Click" class="item-blog" />
<input type="button" value="Reset" class="item-blog-reset" />
Aruna
  • 11,959
  • 3
  • 28
  • 42
0

Try removing the class instead... And add a temporary one.
;)

$(document).on('click','.item-blog', function(){
    $(this).removeClass("item-blog").addClass("item-blog-disabled");
});

Then, later, you will only have to re-add the class using the item-blog-disabled class.
like:

$(document).find('.item-blog-disabled').removeClass("item-blog-disabled").addClass("item-blog");

So now, the handler is binded to the document which delegates for .item-blog it has.

Giving you the opportunity to remove/add the handler on those elements using a simple class.

Louys Patrice Bessette
  • 33,375
  • 6
  • 36
  • 64