restore event to default action in jquery after event.prenventdefault - javascript

I used this answer to disable arrow and pgdown and pgup keys actions (scrolling). but I need to set actions of this keys to default (scrolling) after event.preventDefault() called in my jquery code.
How can I do this.

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....///
});

To reverse preventDefault(), you need to unbind the original action and then re-call it.
$(document).keydown(function(e) {
e.preventDefault()
// Do stuff until you need to recall the default action
$(this).unbind('keydown').keydown()
})
How to unbind a listener that is calling event.preventDefault() (using jQuery)?

Related

How to stop CodeMirror from moving cursor on keyup?

I want to skip certain, uneditable (XML-)tags in my code, using CodeMirror. In order to do that, I have to 'stop' (preventDefault) the keyup event, do some logic and move the cursor. PreventDefault and codemirrorIgnore don't work or do not do what I need them to do. Do I have to catch the event outside CodeMirror? :(
Does not work:
codeMirror.on('keyup', function (cm, ev) {
ev.codemirrorIgnore = true;
ev.preventDefault();
return false;
});
By using the below code you can handle the up arrow functionality
codeMirror.setOption("extraKeys", {"Up":function()
{
console.log("Key Up pressed");
if(true) // logic to decide whether to move up or not
{
return CodeMirror.PASS;
}
}});
It sounds like what you actually want is markText with the atomic and readOnly options, rather than messing with key events (which won't really prevent the user from entering/editing the text).

Why can't I use addEventListener to stop contextmenu event?

I want to prohibit the right mouse button. But I find that if I write this:
document.addEventListener('contextmenu', function(event) {
return false;
}, false);
It will not work, the event will still work.
But if I write it like this,
document.oncontextmenu = function() {
return false;
}
The right mouse button will not work.
I wish to know why I can't use addEventListener to stop the event contextmenu.
As stated in "Preventing the Browser's Default Action", the return of false value is not enough for preventing default action. You need to call preventDefault() method on Event object:
document.addEventListener('contextmenu', function(event) {
event.preventDefault();
}, true);
DEMO
I believe you need to useCapture, try passing true as the third parameter to
document.addEventListener() and see if that doesn't solve it for you.

Using preventDefault

I've been looking at some code posted by someone and I can't make sense of why he used preventDefault.
var $windows = $('#tgx-window,#tgs-window,#tgm-window,#tgl-window'), $buttons = $('#tgx-button,#tgs-button,#tgm-button,#tgl-button');
$windows.hide();
$buttons.on('click', function(e) {
var $id;
e.preventDefault();
$buttons.removeClass('closebutton');
$id = $('#' + this.id.split('-')[0] + '-window');// Get window id
$windows.slideUp();
if(! $id.is(':visible') ) {
$id.slideDown();
$(this).addClass('closebutton');
}
});
It seems to behave exactly the same with or without it. My best guess so far is that it's common practice to use preventDefault/return false in function bodies.
My question is why he used that method at all?
Oh, yeah. I'm new to JavaScript.
http://jsfiddle.net/62NPt/53/
From the docs:
If this method is called, the default action of the event will not be
triggered.
So if your button is an input submit button for example, the event.preventDefault() will prevent the default behaviour of your button and prevent your form from submitting and reload the page. This is normally helpful when you want to apply AJAX call.
If the button is of type submit and in case of anchor if you use preventDefault() the default action of the event will not be triggered.
If you dont want to stop default action of element then it does not make any difference.

anchor link not working with jquery event.preventDefault;

I need to open popup on click of anchor link with jquery.
here is HTML part
Clear Search
here is Jquery
$("a.clearField").on("click", function(){loadclearSearchPopup()});
function loadclearSearchPopup(obj){
var delay = '';
$(obj).preventDefault;
//popup open code goes here;
return false;
}
I know i can work around by replacing href with href="#"
But i am curious why event.preventDefault and return false not working?
Any help
$(obj).preventDefault;
should be
e.preventDefault();
It's a method of the event, not a property of the jQuery object. Also, the reason that return false is not working is because you are not passing the return value back to the handler
$("a.clearField").on("click", function (e){
var delay = '';
// Prevents the link from being followed
e.preventDefault();
// Prevents following links and propagation (bubbling the event)
// Note that this is a jQuery feature only. In standard DOM event handlers,
// return false is the same as e.preventDefault()
return false;
// But you don't need both
});
Because you have to attach it to event, not $(obj)
event.preventDefault()
#Juan's answer is correct (though I answered 15 sec earlier), but I'd like to show how to do it correctly with some changes to his code
$("a.clearField").click(loadclearSearchPopup);
function loadclearSearchPopup(e){
e.preventDefault();
// ... your code after preventing default action
}
I didn't use anonymous function as far as you have all your code in loadclearSearchPopup()
I used click instead of on('click', ...) assuming that you don't have a lot of links on your page with exactly the same functionality and you will unlikely change it's content
I prevent action on 1st string because maybe later you will need to return some result or break it, and preventing on last string will not execute
Note, that you cannot pass arguments to your function, but you can handle them IN it
FIDDLE

How to reenable event.preventDefault?

I have a web page which I have prevented the default action on all submit buttons, however I would like to re-enable default submit action on a button how can I do this?
I am currently preventing the default action using the following:
$("form").bind("submit", function(e){
e.preventDefault();
});
I have successfully done this using the following:
$(document).ready(function(){
$("form:not('#press')").bind("submit", function(e){
e.preventDefault();
});
But can I do this dynamically when the button is clicked?
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()
});
Either you do what redsquare proposes with this code:
function preventDefault(e) {
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now switching back
$("form#foo").unbind("submit", preventDefault);
Or you assign a form attribute whenever submission is allowed. Something like this:
function preventDefault(e) {
if (event.currentTarget.allowDefault) {
return;
}
e.preventDefault();
}
$("form").bind("submit", preventDefault);
// later, now allowing submissions on the form
$("form#foo").get(0).allowDefault = true;
function(e){ e.preventDefault();
and its opposite
function(e){ return true; }
cheers!
$('form').submit( function(e){
e.preventDefault();
//later you decide you want to submit
$(this).trigger('submit'); or $(this).trigger('anyEvent');
With async actions (timers, ajax) you can override the property isDefaultPrevented like this:
$('a').click(function(evt){
e.preventDefault();
// in async handler (ajax/timer) do these actions:
setTimeout(function(){
// override prevented flag to prevent jquery from discarding event
evt.isDefaultPrevented = function(){ return false; }
// retrigger with the exactly same event data
$(this).trigger(evt);
}, 1000);
}
This is most complete way of retriggering the event with the exactly same data.
I had a similar problem recently. I had a form and PHP function that to be run once the form is submitted. However, I needed to run a javascript first.
// This variable is used in order to determine if we already did our js fun
var window.alreadyClicked = "NO"
$("form:not('#press')").bind("submit", function(e){
// Check if we already run js part
if(window.alreadyClicked == "NO"){
// Prevent page refresh
e.preventDefault();
// Change variable value so next time we submit the form the js wont run
window.alreadyClicked = "YES"
// Here is your actual js you need to run before doing the php part
xxxxxxxxxx
// Submit the form again but since we changed the value of our variable js wont be run and page can reload (and php can do whatever you told it to)
$("form:not('#press')").submit()
}
});
You can re-activate the actions by adding
this.delegateEvents(); // Re-activates the events for all the buttons
If you add it to the render function of a backbone js view, then you can use event.preventDefault() as required.

Categories

Resources