How to unbind a listener that is calling event.preventDefault() (using jQuery)?

JavascriptJqueryEventsPreventdefaultEvent Bubbling

Javascript Problem Overview


jquery toggle calls preventDefault() by default, so the defaults don't work. you can't click a checkbox, you cant click a link etc etc

is it possible to restore the default handler?

Javascript Solutions


Solution 1 - Javascript

In my case:

$('#some_link').click(function(event){
    event.preventDefault();
});

$('#some_link').unbind('click'); worked as the only method to restore the default action.

As seen over here: https://stackoverflow.com/a/1673570/211514

Solution 2 - Javascript

Its fairly simple

Lets suppose you do something like

document.ontouchmove = function(e){ e.preventDefault(); }

now to revert it to the original situation, do the below...

document.ontouchmove = function(e){ return true; }

From this website.

Solution 3 - Javascript

It is not possible to restore a preventDefault() but what you can do is trick it :)

<div id="t1">Toggle</div>
<script type="javascript">
$('#t1').click(function (e){
   if($(this).hasClass('prevented')){
       e.preventDefault();
       $(this).removeClass('prevented');
   }else{
       $(this).addClass('prevented');
   }
});
</script>

If you want to go a step further you can even use the trigger button to trigger an event.

Solution 4 - Javascript

function DoPrevent(e) {
  e.preventDefault();
  e.stopPropagation();
}

// Bind:
$(element).on('click', DoPrevent);

// UnBind:
$(element).off('click', DoPrevent);

Solution 5 - Javascript

in some cases* you can initially return false instead of e.preventDefault(), then when you want to restore the default to return true.

*Meaning when you don't mind the event bubbling and you don't use the e.stopPropagation() together with e.preventDefault()

Also see https://stackoverflow.com/questions/1164132/how-to-reenable-event-preventdefault/1168022#1168022">similar question (also in stack Overflow)

or in the case of checkbox you can have something like:

$(element).toggle(function(){
  $(":checkbox").attr('disabled', true);
  },
function(){
   $(":checkbox").removeAttr('disabled');
}) 

Solution 6 - Javascript

You can restore the default action (if it is a HREF follow) by doing this:

window.location = $(this).attr('href');

Solution 7 - Javascript

if it is a link then $(this).unbind("click"); would re-enable the link clicking and the default behavior would be restored.

I have created a demo JS fiddle to demonstrate how this works:

Here is the code of the JS fiddle:

HTML:

<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<a href="http://jquery.com">Default click action is prevented, only on the third click it would be enabled</a>
<div id="log"></div>

Javascript:

<script>
var counter = 1;
$(document).ready(function(){
$( "a" ).click(function( event ) {
  event.preventDefault();
  
  $( "<div>" )
    .append( "default " + event.type + " prevented "+counter )
    .appendTo( "#log" );
    
    if(counter == 2)
    {
    	$( "<div>" )
    .append( "now enable click" )
    .appendTo( "#log" );
    
    $(this).unbind("click");//-----this code unbinds the e.preventDefault() and restores the link clicking behavior
    }
    else
    {
    	$( "<div>" )
    .append( "still disabled" )
    .appendTo( "#log" );
    }
    counter++;
});
});
</script>

Solution 8 - Javascript

Test this code, I think solve your problem:

event.stopPropagation();

Reference

Solution 9 - Javascript

The best way to do this by using namespace. It is a safe and secure way. Here .rb is the namespace which ensures unbind function works on that particular keydown but not on others.

$(document).bind('keydown.rb','Ctrl+r',function(e){
			e.stopImmediatePropagation();
			return false;
		});

$(document).unbind('keydown.rb');

ref1: http://idodev.co.uk/2014/01/safely-binding-to-events-using-namespaces-in-jquery/

ref2: http://jqfundamentals.com/chapter/events

Solution 10 - Javascript

If the element only has one handler, then simply use jQuery unbind.

$("#element").unbind();

Solution 11 - Javascript

Disable:

document.ontouchstart = function(e){ e.preventDefault(); }

Enable:

document.ontouchstart = function(e){ return true; }

Solution 12 - Javascript

The Event interface's preventDefault() method tells the user agent that if the event does not get explicitly handled, its default action should not be taken as it normally would be. The event continues to propagate as usual, unless one of its event listeners calls stopPropagation() or stopImmediatePropagation(), either of which terminates propagation at once.

Calling preventDefault() during any stage of event flow cancels the event, meaning that any default action normally taken by the implementation as a result of the event will not occur.

You can use Event.cancelable to check if the event is cancelable. Calling preventDefault() for a non-cancelable event has no effect.

window.onKeydown = event => {
    /*
        if the control button is pressed, the event.ctrKey 
        will be the value  [true]
    */

    if (event.ctrKey && event.keyCode == 83) {
        event.preventDefault();
        // you function in here.
    }
}

Solution 13 - Javascript

I had a problem where I needed the default action only after some custom action (enable otherwise disabled input fields on a form) had concluded. I wrapped the default action (submit()) into an own, recursive function (dosubmit()).

var prevdef=true;
var dosubmit=function(){
	if(prevdef==true){
		//here we can do something else first//
		prevdef=false;
		dosubmit();
	}
	else{
		$(this).submit();//which was the default action
	}
};

$('input#somebutton').click(function(){dosubmit()});

Solution 14 - Javascript

Use a boolean:

let prevent_touch = true;
document.documentElement.addEventListener('touchmove', touchMove, false);
function touchMove(event) { 
    if (prevent_touch) event.preventDefault(); 
}

I use this in a Progressive Web App to prevent scrolling/zooming on some 'pages' while allowing on others.

Solution 15 - Javascript

You can set to form 2 classes. After you set your JS script to one of them, when you want to disable your script, you just delete the class with binded script from this form.

HTML:

<form class="form-create-container form-create"> </form>   

JS

$(document).on('submit', '.form-create', function(){ 
..... ..... ..... 
$('.form-create-container').removeClass('form-create').submit();

});

Solution 16 - Javascript

in javacript you can simply like this

const form = document.getElementById('form');
form.addEventListener('submit', function(event){
  event.preventDefault();

  const fromdate = document.getElementById('fromdate').value;
  const todate = document.getElementById('todate').value;

  if(Number(fromdate) >= Number(todate)) {
    alert('Invalid Date. please check and try again!');
  }else{
    event.currentTarget.submit();
  }

});

Solution 17 - Javascript

This should work:

$('#myform').on('submit',function(e){
    if($(".field").val()==''){
        e.preventDefault();
    }
}); 

Solution 18 - Javascript

$('#my_elementtt').click(function(event){
    trigger('click');
});

Solution 19 - Javascript

I'm not sure you're what you mean: but here's a solution for a similar (and possibly the same) problem...

I often use preventDefault() to intercept items. However: it's not the only method of interception... often you may just want a "question" following which behaviour continues as before, or stops. In a recent case I used the following solution:

$("#content").on('click', '#replace', (function(event){ return confirm('Are you sure you want to do that?') }));

Basically, the "prevent default" is meant to intercept and do something else: the "confirm" is designed for use in ... well - confirming!

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser188049View Question on Stackoverflow
Solution 1 - JavascriptklausView Answer on Stackoverflow
Solution 2 - JavascriptfoxybaggaView Answer on Stackoverflow
Solution 3 - JavascriptValView Answer on Stackoverflow
Solution 4 - JavascriptAtaraView Answer on Stackoverflow
Solution 5 - JavascriptadardesignView Answer on Stackoverflow
Solution 6 - JavascriptcrmpiccoView Answer on Stackoverflow
Solution 7 - JavascriptRahul GuptaView Answer on Stackoverflow
Solution 8 - JavascriptAlireza MHView Answer on Stackoverflow
Solution 9 - JavascriptRajkumar BansalView Answer on Stackoverflow
Solution 10 - JavascriptShawn WView Answer on Stackoverflow
Solution 11 - JavascriptBrynner FerreiraView Answer on Stackoverflow
Solution 12 - JavascriptJoão Victor PalmeiraView Answer on Stackoverflow
Solution 13 - JavascriptGyulaView Answer on Stackoverflow
Solution 14 - JavascriptTennisVisualsView Answer on Stackoverflow
Solution 15 - JavascriptDumitru BoaghiView Answer on Stackoverflow
Solution 16 - JavascriptazharView Answer on Stackoverflow
Solution 17 - JavascriptMario RubíView Answer on Stackoverflow
Solution 18 - JavascriptT.ToduaView Answer on Stackoverflow
Solution 19 - Javascriptelb98rmView Answer on Stackoverflow