jquery prevent duplicate function assigned

Viewed 30387

If I need to assign a click function dynamically, is there a way to ensure the click function is only assigned once and not duplicated?

this.click(function(){
    alert('test');
})
6 Answers

This worked for me !

$('.element').on('click', function (event) {
    if(event.isDefaultPrevented()) return;
    event.preventDefault();

    // do something
}

Remove existing click event:

$('body').off('click','.switch-tab');

Add new click event:

$('body').on('click','.switch-tab', function () {
   switch_tab($(this).data('tab_id'));
});
Related