preventDefault() like functionality in javascript - javascript

I have already gone through this question
event.preventDefault() vs. return false
But didn't find my solution. Actually i am using javascript function to go back to previous page that is working fine on click of
<img src="images/backbtn.png">
function
function goBack(){
window.history.back();
}
When i click on <a> it includes # in url which i want to prevent. In jquery we use preventDefault() to stop the default event of an element but is there any similar function in javascript to stop it.
I know i can use javascript:void(0) in href which will solve the problem but there can be many other instances so i want to know about function in javascript.
I tried using return false; but it i write this on top like this
function goBack(){
return false;
window.history.back();
}
Then it stops the function to execute and if i write like this
function goBack(){
window.history.back();
return false;
}
Then no effect from this return false;. I am sure there is some in javascript as jquery is generated from javascript.
Any help would be appreciated. Thanks in advance!

As far as I know, preventDefault() also is a native JS function, so you can use it without jQuery and get same result.
You can read more about it here: MDN: Event.preventDefault()

event.preventDefault() works both in Javasccript and Jquery
If getting the # is the problem and for some reason you really want to use only preventDefault() then you must pass the event into the function and then inside the function use event.preventDefault()
<img src="images/backbtn.png">
Then in your Javascript use this passed event and stop the default behaviour.
function goBack(event){
event.preventDefault();
window.history.back();
}

To add to the answers, return false in jquery does both event.preventDefault and event.stopPropagation()
From jquery source code, jquery.event.dispatch
if ( ret !== undefined ) {
if ( (event.result = ret) === false ) {
event.preventDefault();
event.stopPropagation();
}
}
Both preventDefault and stopPropagation are available in Javascript.
For IE < 9, event.stopPropagation can be done by event.cancelBubble = true
and event.preventDefault can be done by event.returnValue = false

preventDefault exists in javascript, but if you are interested in a jQuery like solution you need to take care of compatibility issues.
A different solution, considering the compatibility issues with old browsers, is:
function goBack(evt){
var e = evt || window.event;
if (e !== undefined) {
if (e.preventDefault) {
e.preventDefault();
} else { // IE
e.returnValue = false;
}
}
window.history.back();
}
<img src="images/backbtn.png">

Related

event.returnValue = false to replace preventdefault not working in IE 11

The following works fine everywhere except in IE 11:
if( event.keyCode == 18 )
{
event.preventDefault ? event.preventDefault() : event.returnValue = false
altcurrentstate = "keyisdown";
Xmouse = x;
Ymouse= y;
return false;
}
I also tried the others ways offered in this site but nope, can't seems to preventDefault in IE 11 no matter what, for the alt and arrow keys. The event.returnValue = false; trick is not working either. Not working with return false either...
Try actually return false in your callback function.
Perhaps you need to make your event cancelable using the initEvent() method.
According to the remarks at the bottom of this page:
If you cannot cancel the event, calling IDOMEvent::preventDefault has no effect.
When you create a custom event by using the IDocumentEvent::createEvent method, you can set the IDOMEvent::cancelable property by using the IDOMEvent::initEvent method.

Significance of return false statement inside addEventListener function definition

I was going through following JavaScript code Snippet and I am unable to figure out the significance of return false statement in fire() function.
var x=document.getElementById("OK_BUT");
x.addEventListener("click", fire, false);
Definition of Fire Function
function fire(e)
{
....................
.....................
return false;/*=> What is the significance of this Statement??*/
}
I think its due to browser compatibility. Would be great if somebody explains its significance!!
It's the same as e.preventDefault();
More info can be found in this thread:
event.preventDefault() vs. return false
This would possibly be added to prevent the default behavior happening on the form submission of the click event, i.e. ensuring the page doesn't post back once the event has been fired. e.preventDefault() would accomplish the same desired behavior.

How to register document.onkeypress event

I want to register keypress events for a document using javascript.
I have used:
document.attachEvent("onkeydown", my_onkeydown_handler);
It works fine with IE,
but not with Firefox and Chrome.
I also tried:
document.addEventListener("onkeydown", my_onkeydown_handler, true);
// (with false value also)
But it still doesn't work with Firefox and Chrome.
Is there a solution, am I missing something?
You are looking for:
EDIT:
Javascript:
document.addEventListener("keydown", keyDownTextField, false);
function keyDownTextField(e) {
var keyCode = e.keyCode;
if(keyCode==13) {
alert("You hit the enter key.");
} else {
alert("Oh no you didn't.");
}
}
DEMO: JSFIDDLE
You are probably looking for:
document.body.addEventListener('keydown', function (e) {
alert('hello world');
});​​​​​​​
But it is almost certainly going to be worth your time to use an existing library to abstract over the problems of the many browsers out there.
Please go through following links for detailed description.
https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener?redirectlocale=en-US&redirectslug=DOM%3Aelement.addEventListener
http://www.reloco.com.ar/mozilla/compat.html
In short, write handler as
function myFunction(e)
{
///For IE
if(!e)
e=window.event;
// use e as event in rest of code.
}

Multiple OnBeforeUnload

I am writing a JS which is used as a plugin. The JS has an onbeforeunload event.
I want suggestions so that my onbeforeunload event doesn't override the existing onbeforeunload event (if any). Can I append my onbeforeunload to the existing one?
Thanks.
I felt this has not been answered completely, because no examples were shown using addEventListener (but The MAZZTer pointed out the addEventListener solution though). My solution is the same as Julian D. but without using jQuery, only native javascript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Before Unload</title>
</head>
<body>
<p>Test</p>
<script>
window.addEventListener('beforeunload', function (event) {
console.log('handler 1')
event.preventDefault()
event.returnValue = ''
});
window.addEventListener('beforeunload', function (event) {
console.log('handler 2')
});
</script>
</body>
</html>
In this example, both listeners will be executed. If any other beforeunload listeners were set, it would not override them. We would get the following output (order is not guaranteed):
handler 1
handler 2
And, importantly, if one or more of the event listener does event.preventDefault(); event.returnValue = '', a prompt asking the user if he really wants to reload will occur.
This can be useful if you are editing a form and at the same time you are downloading a file via ajax and do not want to lose data on any of these action. Each of these could have a listener to prevent page reload.
const editingForm = function (event) {
console.log('I am preventing losing form data')
event.preventDefault()
event.returnValue = ''
}
const preventDownload = function (event) {
console.log('I am preventing a download')
event.preventDefault()
event.returnValue = ''
}
// Add listener when the download starts
window.addEventListener('beforeunload', preventDownload);
// Add listener when the form is being edited
window.addEventListener('beforeunload', editingForm);
// Remove listener when the download ends
window.removeEventListener('beforeunload', preventDownload);
// Remove listener when the form editing ends
window.removeEventListener('beforeunload', editingForm);
You only need to take care of this if you are not using event observing but attach your onbeforeunload handler directly (which you should not). If so, use something like this to avoid overwriting of existing handlers.
(function() {
var existingHandler = window.onbeforeunload;
window.onbeforeunload = function(event) {
if (existingHandler) existingHandler(event);
// your own handler code here
}
})();
Unfortunately, you can't prevent other (later) scripts to overwrite your handler. But again, this can be solved by adding an event listener instead:
$(window).unload(function(event) {
// your handler code here
});
My idea:
var callbacks = [];
window.onbeforeunload = function() {
while (callbacks.length) {
var cb = callbacks.shift();
typeof(cb)==="function" && cb();
}
}
and
callbacks.push(function() {
console.log("callback");
});
Try this:
var f = window.onbeforeunload;
window.onbeforeunload = function () {
f();
/* New code or functions */
}
You can modify this function many times , without losing other functions.
If you bind using jQuery, it will append the binding to the existing list, so there is no need to worry.
From the jQuery Docs on() method:
As of jQuery 1.4, the same event handler can be bound to an element
multiple times.
function greet(event) { alert("Hello "+event.data.name); }
$("button").on("beforeunload", { name: "Karl" }, greet);
$("button").on("beforeunload", { name: "Addy" }, greet);
You can use different javascript frameworks like jquery or you could probably add a small event add handler to do this. Like you have an object thatcontains a number of functions that you have added and then in the onbefore unload you run the added functions. So when you want to add a new function to the event you add it to your object instead.
something like this:
var unloadMethods = [];
function addOnBeforeUnloadEvent(newEvent) { //new Event is a function
unloadMethods[unloadMethods.length] = newEvent;
}
window.onbeforeunload = function() {
for (var i=0; i<unloadMethods.length; i++) {
if(typeof unloadMethods[i] === "function") {unloadMethods[i]();}
}
}
Those frameworks mentioned use addEventListener internally. If you are not using a framework, use that.
https://developer.mozilla.org/en-US/docs/DOM/element.addEventListener
For older versions of IE you should have a fallback to use attachEvent instead:
http://msdn.microsoft.com/en-us/library/ie/ms536343(v=vs.85).aspx
I liked Marius's solution, but embellished on it to cater for situations where the var f is null, and to return the first string returned by any function in the chain:
function eventBeforeUnload(nextFN){
//some browsers do not support methods in eventAdd above to handle window.onbeforeunload
//so this is a way of attaching more than one event listener by chaining the functions together
//The onbeforeunload expects a string as a return, and will pop its own dialog - this is browser behavior that can't
//be overridden to prevent sites stopping you from leaving. Some browsers ignore this text and show their own message.
var firstFN = window.onbeforeunload;
window.onbeforeunload = function () {
var x;
if (firstFN) {
//see if the first function returns something
x = firstFN();
//if it does, return that
if (x) return x;
}
//return whatever is returned from the next function in the chain
return nextFN();
}
}
In your code where required use it as such
eventBeforeUnload(myFunction);
//or
eventBeforeUnload(function(){if(whatever) return 'unsaved data';);

event.preventDefault() function not working in IE

Following is my JavaScript (mootools) code:
$('orderNowForm').addEvent('submit', function (event) {
event.preventDefault();
allFilled = false;
$$(".required").each(function (inp) {
if (inp.getValue() != '') {
allFilled = true;
}
});
if (!allFilled) {
$$(".errormsg").setStyle('display', '');
return;
} else {
$$('.defaultText').each(function (input) {
if (input.getValue() == input.getAttribute('title')) {
input.setAttribute('value', '');
}
});
}
this.send({
onSuccess: function () {
$('page_1_table').setStyle('display', 'none');
$('page_2_table').setStyle('display', 'none');
$('page_3_table').setStyle('display', '');
}
});
});
In all browsers except IE, this works fine. But in IE, this causes an error. I have IE8 so while using its JavaScript debugger, I found out that the event object does not have a preventDefault method which is causing the error and so the form is getting submitted. The method is supported in case of Firefox (which I found out using Firebug).
Any Help?
in IE, you can use
event.returnValue = false;
to achieve the same result.
And in order not to get an error, you can test for the existence of preventDefault:
if(event.preventDefault) event.preventDefault();
You can combine the two with:
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
If you bind the event through mootools' addEvent function your event handler will get a fixed (augmented) event passed as the parameter. It will always contain the preventDefault() method.
Try out this fiddle to see the difference in event binding.
http://jsfiddle.net/pFqrY/8/
// preventDefault always works
$("mootoolsbutton").addEvent('click', function(event) {
alert(typeof(event.preventDefault));
});
// preventDefault missing in IE
<button
id="htmlbutton"
onclick="alert(typeof(event.preventDefault));">
button</button>
For all jQuery users out there you can fix an event when needed. Say that you used HTML onclick=".." and get a IE specific event that lacks preventDefault(), just use this code to get it.
e = $.event.fix(e);
After that e.preventDefault(); works fine.
I know this is quite an old post but I just spent some time trying to make this work in IE8.
It appears that there are some differences in IE8 versions because solutions posted here and in other threads didn't work for me.
Let's say that we have this code:
$('a').on('click', function(event) {
event.preventDefault ? event.preventDefault() : event.returnValue = false;
});
In my IE8 preventDefault() method exists because of jQuery, but is not working (probably because of the point below), so this will fail.
Even if I set returnValue property directly to false:
$('a').on('click', function(event) {
event.returnValue = false;
event.preventDefault();
});
This also won't work, because I just set some property of jQuery custom event object.
Only solution that works for me is to set property returnValue of global variable event like this:
$('a').on('click', function(event) {
if (window.event) {
window.event.returnValue = false;
}
event.preventDefault();
});
Just to make it easier for someone who will try to convince IE8 to work. I hope that IE8 will die horribly in painful death soon.
UPDATE:
As sv_in points out, you could use event.originalEvent to get original event object and set returnValue property in the original one. But I haven't tested it in my IE8 yet.
Mootools redefines preventDefault in Event objects. So your code should work fine on every browser. If it doesn't, then there's a problem with ie8 support in mootools.
Did you test your code on ie6 and/or ie7?
The doc says
Every event added with addEvent gets the mootools method automatically, without the need to manually instance it.
but in case it doesn't, you might want to try
new Event(event).preventDefault();
if (e.preventDefault) {
e.preventDefault();
} else {
e.returnValue = false;
}
Tested on IE 9 and Chrome.
To disable a keyboard key after IE9, use : e.preventDefault();
To disable a regular keyboard key under IE7/8, use : e.returnValue = false; or return false;
If you try to disable a keyboard shortcut (with Ctrl, like Ctrl+F) you need to add those lines :
try {
e.keyCode = 0;
}catch (e) {}
Here is a full example for IE7/8 only :
document.attachEvent("onkeydown", function () {
var e = window.event;
//Ctrl+F or F3
if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
//Prevent for Ctrl+...
try {
e.keyCode = 0;
}catch (e) {}
//prevent default (could also use e.returnValue = false;)
return false;
}
});
Reference : How to disable keyboard shortcuts in IE7 / IE8
Here's a function I've been testing with jquery 1.3.2 and 09-18-2009's nightly build. Let me know your results with it. Everything executes fine on this end in Safari, FF, Opera on OSX. It is exclusively for fixing a problematic IE8 bug, and may have unintended results:
function ie8SafePreventEvent(e) {
if (e.preventDefault) {
e.preventDefault()
} else {
e.stop()
};
e.returnValue = false;
e.stopPropagation();
}
Usage:
$('a').click(function (e) {
// Execute code here
ie8SafePreventEvent(e);
return false;
})
preventDefault is a widespread standard; using an adhoc every time you want to be compliant with old IE versions is cumbersome, better to use a polyfill:
if (typeof Event.prototype.preventDefault === 'undefined') {
Event.prototype.preventDefault = function (e, callback) {
this.returnValue = false;
};
}
This will modify the prototype of the Event and add this function, a great feature of javascript/DOM in general. Now you can use e.preventDefault with no problem.
return false in your listener should work in all browsers.
$('orderNowForm').addEvent('submit', function () {
// your code
return false;
}
FWIW, in case anyone revisits this question later, you might also check what you are handing to your onKeyPress handler function.
I ran into this error when I mistakenly passed onKeyPress(this) instead of onKeyPress(event).
Just something else to check.
I was helped by a method with a function check. This method works in IE8
if(typeof e.preventDefault == 'function'){
e.preventDefault();
} else {
e.returnValue = false;
}

Categories

Resources