2

I'm trying too take off the event from only this element , if I try $(this).off('event'); they take off event from all elements and $(this).off('click'); don't work

$(document).on('click', '.text', function (event) {
    var box = "<div class = 'box'></div>";
    $(box).insertAfter("#body");
    $(this).off('event');
});
The Process
  • 5,913
  • 3
  • 30
  • 41
John
  • 483
  • 3
  • 9
  • 18
  • $(this).off(event); * – John Mar 30 '16 at 19:15
  • 1
    If you have to use event delegation, then consider to remove class `.text` from current element. Take a look here http://stackoverflow.com/questions/30512253/remove-jquery-delegated-event-handler-on-specific-object – The Process Mar 30 '16 at 19:21
  • ohhh, i understand the logic now, i need to remove the class or id then if i want to let user click again in this element i just put the class or id back – John Mar 30 '16 at 19:36
  • BTW, you also have an option to namespace an event `$( element ).on( 'click.myNamespace', {})` and turn it off using `$( element ).on( '.myNamespace'` (But the use of classes as suggested is much better) – Alon Eitan Mar 30 '16 at 19:38
  • If you don't have to use event delegation, you can do something like this: http://jsbin.com/fewida/edit?html,js,console,output – The Process Mar 30 '16 at 19:40

1 Answers1

0

Try:

$(document).on('click', '.text', myEventHandler);

function myEventHandler(e){
  $(this).off('click', myEventHandler);
  var box = "<div class = 'box'></div>";
  $(box).insertAfter("#body");
}
univ
  • 717
  • 4
  • 12