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

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?

This question is related to javascript jquery events preventdefault event-bubbling

The answer is


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

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

Disable:

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

Enable:

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

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

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


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


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.
    }
}

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 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');
}) 

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.


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

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

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

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

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!


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();

});

Test this code, I think solve your problem:

event.stopPropagation();

Reference


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.


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.


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>

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


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()});

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to events

onKeyDown event not working on divs in React Detect click outside Angular component Angular 2 Hover event Global Events in Angular How to fire an event when v-model changes? Passing string parameter in JavaScript function Capture close event on Bootstrap Modal AngularJs event to call after content is loaded Remove All Event Listeners of Specific Type Jquery .on('scroll') not firing the event while scrolling

Examples related to preventdefault

React onClick and preventDefault() link refresh/redirect? Bootstrap 3 - disable navbar collapse How to preventDefault on anchor tags? Stop form from submitting , Using Jquery Prevent Default on Form Submit jQuery What's the difference between event.stopPropagation and event.preventDefault? What is the opposite of evt.preventDefault(); How to unbind a listener that is calling event.preventDefault() (using jQuery)? event.preventDefault() function not working in IE

Examples related to event-bubbling

Prevent scrolling of parent element when inner element scroll position reaches top/bottom? What is event bubbling and capturing? How to unbind a listener that is calling event.preventDefault() (using jQuery)? How do I hide an element on a click event anywhere outside of the element?