I use on() JQuery function and preventDefault() for prevent anchor default action. I can not understand off() JQuery function. can I use off('click') instead of:
$('.anchor').on('click', function(e) {
e.preventDefault();
});
I mean, can I use this for prevent default action of anchor?
$('.anchor').off('click');
off : disable the eventHandler so no function can be execute on click preventdefault : disable the default eventHandler but you can use your own function.
They are logically very different.
preventDefault() stops the browser from acting on the event behaviour but still executes the JS code. For example, in the below, the URL the .anchor element points to will not be transferred, however the JS code will still run:
$('.anchor').on('click',function(e){
e.preventDefault();
console.log('the browser wont redirect, but you will see this line in the console')
});
On the other hand, off() completely removes any event handler of the given type from the element. In this case, the browser will be transferred to the given URL on click and no JS code will be run.
$('.anchor').off('click');