How to Unbind a Listener That Is Calling Event.Preventdefault() (Using Jquery)

event.preventDefault() on first click then remove

You can pass false to one():

$(".subnav a").one("click", false);

Passing false instead of a handler is equivalent to passing a handler that returns false, effectively stopping the event's propagation and preventing its default behavior.

This is explained in the documentation for bind():

In jQuery 1.4.3 you can now pass in false in place of an event
handler. This will bind an event handler equivalent to: function() {
return false; }
.

How to reenable event.preventDefault?

You would have to unbind the event and either rebind to a separate event that does not preventDefault or just call the default event yourself later in the method after unbinding.
There is no magical event.cancelled=false;

As requested

 $('form').submit( function(ev){

ev.preventDefault();

//later you decide you want to submit
$(this).unbind('submit').submit()

});

How to disable preventDefault in an event listener using Vanilla JS

I think you should return true/false from your validateForm() function to prevent/submit the form.

1. You have to return value from the function in the html markup:

<form id="contact_form" onsubmit="return validateForm();">

2. Return true/false from your validateForm() based on validation.

function validateForm() {
var error = "";
................
................
................
if (error != "") {
document.getElementById("errorDiv").style.display = "block";
document.getElementById("errorDiv").innerHTML = "<b>There wer error(s) in the form, please complete all required fields</b>" + error;
return false;

} else {
return true;
}
}

  1. Does not required to prevent form submit so remove this code.

    var element = document.querySelector('form');
    element.addEventListener('submit', event => {
    event.preventDefault();
    });

restore event to default action in jquery after event.prenventdefault

Hard to answer without better specifics, but if I understand what you have properly if you have something you can track state with you can preventDefault when you wish to block this behavior and let it fall through otherwise:

Psudocode:

var state = {
blockArrows: true;
}

$('#my_widget').keydown(function(e) {
if(state.blockArrows) {
e.preventDefault();
}
// ...else allow the event to do its normal thing....///
});


Related Topics



Leave a reply



Submit