issue with event.returnValue=false; in js - javascript

<HTML>
<HEAD>
<TITLE>Statements with returnValue</TITLE>
</HEAD>
<BODY>
Drive C
</BODY>
</HTML>
Question:
We have this line: event.returnValue=false; but why alert() still got excuted? then, what is the purpose to use event.returnValue=false;?

There are two ways to prevent the default behaviour of the click (in this case, navigating to "c:"):
return false from the event handler. This will immediately exit the current event handler, and prevent any further actions.
Set event.returnValue = false. This does not immediately stop the current event handler (ie. onclick), but once it completes, any further actions will be prevented.
Since event.returnValue is not supported in all browsers, I'd definitely recommend using return false instead - just don't forget that it needs to be at the end of your onclick handler.

The purpose of event.returnValue is here: MSDN
It does not, however, change the execution order. You would need to have a return statement to change the order of execution:
<HTML>
<HEAD>
<TITLE>Statements with returnValue</TITLE>
</HEAD>
<BODY>
Drive C
</BODY>
</HTML>

Related

What is difference between onbeforeunload in body tag and beforeunload?

What is difference between
<body onbeforeunload="return myFunction()">
and
$(window).on('beforeunload', function () {
myFunction();
});
The onbeforeunload event occurs when the document is about to be unloaded.
This event allows you to display a message in a confirmation dialog box to inform the user whether he/she wants to stay or leave the current page shows in below code snippet.
The default message that appears in the confirmation box, is different in different browsers. However, the standard message is something like "Are you sure you want to leave this page?". This message cannot be removed.
<!DOCTYPE html>
<html>
<body onbeforeunload="return myFunction()">
<p>Reload this page, or click on the link below to invoke the onbeforeunload event.</p>
Click here to go to stackoverflow.com
<script>
function myFunction() {
return "Write something clever here...";
}
</script>
</body>
</html>
The beforeunload event is fired when the window, the document and its resources are about to be unloaded. The document is still visible and the event is still cancelable at this point.
window.addEventListener('beforeunload', (event) => {
// Cancel the event as stated by the standard.
event.preventDefault();
// Chrome requires returnValue to be set.
event.returnValue = '';
});
There might be a difference in when the function is bound to the event depending on where your jQuery code is. If it's inline in the HEAD section than the jQuery code will run earlier binding the event sooner, otherwise under almost all circumstances the body attribute will bind the function to the event earlier.
Your code probably won't work in modern browsers. This hook is mostly used by less reputable often malicious sites that want to prevent the user from leaving their page and trick them into buying something. Adblockers often prevent the hook in the body tag from firing altogether.
You used to be able to return a string from the function to customize the message but this is now disabled in most browsers. All you can do is confirm that the user wants to leave the page. For future proofing I would put the following code in my head section:
<script>
window.addEventListener(function(event) {
event.preventDefault();
// ... stuff ...
return 'reason';
})
</script>
Event though there are legitimate, non sketchy reasons to use this event, I would avoid it unless it's absolutely necessary. There is no guarantee the event will fire and there is a chance that the user clicks the confirm button (or has a setting/extension to always confirm) before your de initialization code has a chance to run.

Issue with global variables when using event handlers(basic Javascript)

Recently i got stuck on an issue when using DOM event handlers. Next i´ll describe the problem related stuff:
The code
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body>
<form >
<input id="b1" type="submit" value="Click" />
</form>
<script>
//global variable
var v= 0;
var b1= document.getElementById("b1");
b1.addEventListener("click", f1, false);
function f1() {
window.alert(++v);
}
</script>
</body>
</html>
How the code should work?
When the button(b1) is pressed, the global variable(v) increases its value progressively for each new click of the button.The window will alert the new value.
The problem:
The variable doesnt keep its latest value.For example, when i click the button twice, the window should alert 2 but instead im still getting 1.
Assertions:
The global variable(v) should keep the changes done to it inside a function.This is due the fact that im using it directly on the function,without using an argument.
Notes:
When i invoke the function twice directly on the code it works correctly(instead of the handler).
f1();//1
f1();//2
I´ve tested it with Chrome and Firefox.
So, what´s happening here? why doesn´t it works correctly? does the event handler works differently with the global variables?
Hope you guys can help me! Thanks!
You need to add a form onsubmit handler that cancels the submit. The value is being reset because the page reloaded.
<form onsubmit="return false;">
<input id="b1" type="submit" value="Click" />
</form>
That would do it.
Here's a jsfiddle. Try removing and adding the onsubmit handler to see it more clearly on the jsfiddle.
You could optionally also switch the click event out for an onsubmit on the form and use preventDefault on your onsubmit event instead of using the onsubmit in the HTML, at least in modern browsers. In older versions of IE you had to do it a little differently.
function f1(event) {
event.preventDefault();
window.alert(++v);
}
This issue is that the submit button is submitting your form, most likely causing the page to refresh and reset v to 0. You can prevent this behaviour with the preventDefault method on the event object that gets passed to your callback function:
//global variable
var v= 0;
var b1 = document.getElementById("b1");
b1.addEventListener("click", f1, false);
// e is the event object
function f1(e) {
// calling preventDefault will prevent the form from being submitted
e.preventDefault();
console.log("b1 click", ++v)
}
Just a stylistic note, it's confusing to use ++v. You're better off using v += 1;
As already established, you are seeing this behavior because clicking the button submits the form and reloads the page.
The simplest solution is to remove the <form> element.

Order of execution of jquery event handlers in respect to (inline) javascript event handlers

Correct me if I am wrong, but seems to me jQuery event handling is completely separate from the javascript event handling. I know that the order of executing jQuery and javascript event handlers themselves is undefined, but can the assumption be made that all javascript handlers will execute before jQuery ones?
In the example given in an answer to this question that seems to be the case.
Also, is there any preference on executing inline javascript event handlers in respect to bound ones?
For clarification, I am asking all of this because I encountered a problem where I have an inline event handler on onClick event of an <a> element that calls the submit() method of an enclosing form. Just before submitting the form, I want to dynamically add some hidden inputs to the form. Right now I am doing this:
var preSubmit = function preSubmit()
{
// add inputs
}
var oldSubmit = form.submit;
form.submit = function newSubmit()
{
preSubmit();
oldSubmit.call(form, arguments);
}
But I'm really wondering if there is a more elegant way and I really need some clarification on this.
I'm not sure about the specs but I presume that event handlers are just queued in the same order as you define them. Inline handlers are defined right in the DOM node so nothing else can go earlier.
The most elegant way is to write all your JavaScript in an unobtrusive way, i.e., keep it separated from HTML (you appear to be mixing programming styles). Whatever, you can intercept form submission by attaching an onsubmit handler to the form:
$("form").submit(function(){
// Do stuff
return true;
});
Update
I've done some testing and it appears that an onsubmit handler attached to a form via jQuery does not get triggered when you call the DOM's submit() method somewhere else. Here's a workaround:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head><title></title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript"><!--
jQuery(function($){
$("a").each(function(i, a){
a.onclick = function(){ // Remove previous handlers
alert("I will no longer submit the form");
$(this).closest("form").submit();
};
});
$("form").submit(function(){
alert("I'll take care myself, thank you");
$("input[name=foo]").val("Another value");
return true;
});
});
//--></script>
</head>
<body>
<form action="" method="get">
<input type="text" name="foo" value="Default value">
Submit form
</form>
</body>
</html>
There are two solutions: Wrap the submit function of the form or the onClick handler of the link. I'm not aware that jQuery offers a "wrap existing function" API.
As for the run order, jQuery is JavaScript, so the handlers run when the browser runs them. That's not something specific to jQuery, except when the API states that something is run asynchronously.
Asides from the detail of your question, you could just add an onsubmit event, which will be called before the form submits anyway...

How to fire "onload" event on document in IE

I am currently developing Unit Tests for a Javascript method that detects the readiness of the document. This code is already at framework level, so please avoid mentions of this being already implemented in jQuery or another library.
I have successfully simulated the 'readystatechange' change event with the following code:
var event;
event = document.createEventObject();
event.type = 'readystatechange';
document.fireEvent('onreadystatechange',event);
I failed to do the same for the 'load' event. The following code results in an invalid argument error in IE7, thrown by the call to fireEvent on the last line:
event = document.createEventObject();
event.type = 'load';
document.fireEvent('onload',event);
Has anyone done this, or failed to do this before? I am also interested in any suggestion to fire the event in a different way.
Edit: following the suggestion by Crescent Fresh, I changed my code to:
event = document.createEventObject();
event.type = 'load';
document.body.fireEvent('onload',event);
There is no more error, but the listener for 'onload' does not fire. Here is how I configured it:
document.attachEvent('onload',listener);
According to this page at MSDN, there's no onload event for document.
You want either window.onload or document.body.onload. These are identical in IE: for historical reasons, <body onload="..."> actually sets window.onload, so MS decided to make document.body.onload an alias of window.onload.
The problem with this is - as Eric mentioned in the comments - that there doesn't seem to be a way to manually fire window events, which means that there might not be a solution for Eric's problem.
For some reason, it appears that IE overrides the onload property of window with an empty object after the DOM is loaded. At least that is the case when you try to access it from within any event handler of a DOM element...
<!DOCTYPE html>
<html>
<head>
<title>Test by Josh</title>
<script type="text/javascript">
window.onload = function() {
alert("Test");
}
alert(typeof window.onload);
</script>
</head>
<body>
<h1 onclick="alert(typeof window.onload);">Test</h1>
</body>
</html>
In this situation, you'll see that window.onload is recognized as a function initially, then you see the "Test" alert. When you click on the heading, you'll see that window.onload is now an object. I tried iterating through the properties of the object, but it's empty. This is not cool.
One lame workaround is to grab the function in the accessible scope and assign it to a different property that you can fire at your convenience...
<!DOCTYPE html>
<html>
<head>
<title>Test by Josh</title>
<script type="text/javascript">
window.onload = function() {
alert("Test");
}
</script>
</head>
<body>
<h1 onclick="window.onloadfix()">Test</h1>
<!-- Could potentially be injected via server-side include if needed -->
<script type="text/javascript">
window.onloadfix = function() {
window.onload();
}
</script>
</body>
</html>
I can't think of any other way to address this issue right now.
The load event will fire when the document (including external resources such as images) has fully loaded, and not before.
What results are you getting from your attempts to fire readystatechange? Does the readyState value actually change at all? Whether or not, that's not of much use either: either you fire the event with a readyState that hasn't changed, or you do so with a readyState that isn't a valid reflection of the state of the document.

event.preventDefault() vs. return false

When I want to prevent other event handlers from executing after a certain event is fired, I can use one of two techniques. I'll use jQuery in the examples, but this applies to plain-JS as well:
1. event.preventDefault()
$('a').click(function (e) {
// custom handling here
e.preventDefault();
});
2. return false
$('a').click(function () {
// custom handling here
return false;
});
Is there any significant difference between those two methods of stopping event propagation?
For me, return false; is simpler, shorter and probably less error prone than executing a method. With the method, you have to remember about correct casing, parenthesis, etc.
Also, I have to define the first parameter in callback to be able to call the method. Perhaps, there are some reasons why I should avoid doing it like this and use preventDefault instead? What's the better way?
return false from within a jQuery event handler is effectively the same as calling both e.preventDefault and e.stopPropagation on the passed jQuery.Event object.
e.preventDefault() will prevent the default event from occuring, e.stopPropagation() will prevent the event from bubbling up and return false will do both. Note that this behaviour differs from normal (non-jQuery) event handlers, in which, notably, return false does not stop the event from bubbling up.
Source: John Resig
Any benefit to using event.preventDefault() over "return false" to cancel out an href click?
From my experience, there is at least one clear advantage when using event.preventDefault() over using return false. Suppose you are capturing the click event on an anchor tag, otherwise which it would be a big problem if the user were to be navigated away from the current page. If your click handler uses return false to prevent browser navigation, it opens the possibility that the interpreter will not reach the return statement and the browser will proceed to execute the anchor tag's default behavior.
$('a').click(function (e) {
// custom handling here
// oops...runtime error...where oh where will the href take me?
return false;
});
The benefit to using event.preventDefault() is that you can add this as the first line in the handler, thereby guaranteeing that the anchor's default behavior will not fire, regardless if the last line of the function is not reached (eg. runtime error).
$('a').click(function (e) {
e.preventDefault();
// custom handling here
// oops...runtime error, but at least the user isn't navigated away.
});
This is not, as you've titled it, a "JavaScript" question; it is a question regarding the design of jQuery.
jQuery and the previously linked citation from John Resig (in karim79's message) seem to be the source misunderstanding of how event handlers in general work.
Fact: An event handler that returns false prevents the default action for that event. It does not stop the event propagation. Event handlers have always worked this way, since the old days of Netscape Navigator.
Event handler content attributes and event handler IDL attributes that returns false prevents the default action for that event handler.
What happens in jQuery is not the same as what happens with event handlers. DOM event listeners and MSIE "attached" events are a different matter altogether.
For further reading, see the[ [W3C DOM 2 Events documentation]][1].
Generally, your first option (preventDefault()) is the one to take, but you have to know what context you're in and what your goals are.
Fuel Your Coding has a great article on return false; vs event.preventDefault() vs event.stopPropagation() vs event.stopImmediatePropagation().
When using jQuery, return false is doing 3 separate things when you call it:
event.preventDefault();
event.stopPropagation();
Stops callback execution and returns immediately when called.
See jQuery Events: Stop (Mis)Using Return False for more information and examples.
You can hang a lot of functions on the onClick event for one element. How can you be sure the false one will be the last one to fire? preventDefault on the other hand will definitely prevent only the default behavior of the element.
I think
event.preventDefault()
is the w3c specified way of canceling events.
You can read this in the W3C spec on Event cancelation.
Also you can't use return false in every situation. When giving a javascript function in the href attribute and if you return false then the user will be redirected to a page with false string written.
I think the best way to do this is to use event.preventDefault() because if some exception is raised in the handler, then the return false statement will be skipped and the behavior will be opposite to what you want.
But if you are sure that the code won't trigger any exceptions, then you can go with any of the method you wish.
If you still want to go with the return false, then you can put your entire handler code in a try catch block like below:
$('a').click(function (e) {
try{
your code here.........
}
catch(e){}
return false;
});
The main difference between return false and event.preventDefault() is that your code below return false will not be executed and in event.preventDefault() case your code will execute after this statement.
When you write return false it do the following things for you behind the scenes.
* Stops callback execution and returns immediately when called.
* event.stopPropagation();
* event.preventDefault();
e.preventDefault();
It simply stops the default action of an element.
Instance Ex.:-
prevents the hyperlink from following the URL, prevents the submit button to submit the form. When you have many event handlers and you just want to prevent default event from occuring, & occuring from many times,
for that we need to use in the top of the function().
Reason:-
The reason to use e.preventDefault(); is that in our code so something goes wrong in the code, then it will allow to execute the link or form to get submitted or allow to execute or allow whatever action you need to do. & link or submit button will get submitted & still allow further propagation of the event.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Preventsss page from redirect
<script type="text/javascript">
function doSomethingElse(){
console.log("This is Test...");
}
$("a").click(function(e){
e.preventDefault();
});
</script>
</body>
</html>
return False;
It simply stops the execution of the function().
"return false;" will end the whole execution of process.
Reason:-
The reason to use return false; is that you don't want to execute the function any more in strictly mode.
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
Blah
<script type="text/javascript">
function returnFalse(){
console.log("returns false without location redirection....")
return false;
location.href = "http://www.google.com/";
}
</script>
</body>
</html>
Basically, this way you combine things because jQuery is a framework which mostly focuses on HTML elements, you basically preventing the default, but at the same time, you stop propagation to bubble up.
So we can simply say, return false in jQuery is equal to:
return false is e.preventDefault AND e.stopPropagation
But also don't forget it's all in jQuery or DOM related functions, when you run it on the element, basically, it prevents everything from firing including the default behaviour and propagation of the event.
Basically before starting using return false;, first understand what e.preventDefault(); and e.stopPropagation(); do, then if you think you need both at the same time, then simply use it.
So basically this code below:
$('div').click(function () {
return false;
});
is equal to this code:
$('div').click(function (event) {
event.preventDefault();
event.stopPropagation();
});
From my experience event.stopPropagation() is mostly used in CSS effect or animation works, for instance when you have hover effect for both card and button element, when you hover on the button both card and buttons hover effect will be triggered in this case, you can use event.stopPropagation() stop bubbling actions, and event.preventDefault() is for prevent default behaviour of browser actions. For instance, you have form but you only defined click event for the submit action, if the user submits the form by pressing enter, the browser triggered by keypress event, not your click event here you should use event.preventDefault() to avoid inappropriate behavior. I don't know what the hell is return false; sorry.For more clarification visit this link and play around with line #33 https://www.codecademy.com/courses/introduction-to-javascript/lessons/requests-i/exercises/xhr-get-request-iv
My opinion from my experience saying, that it is always better to use
event.preventDefault()
Practically
to stop or prevent submit event, whenever we required rather than return false
event.preventDefault() works fine.
preventDefault() and return false are different ways to prevent the default event from happening.
For example, when a user clicks on an external link, we should display a confirmation modal that asks the user for redirecting to the external website or not:
hyperlink.addEventListener('click', function (e) {
// Don't redirect the user to the link
e.preventDefault();
});
Or we don't want to submit the form when clicking its submit button. Instead, we want to validate the form first:
submitButton.addEventListener('click', function (e) {
// Don't submit the form when clicking a submit
e.preventDefault();
});
Differences
return false doesn't have any effect on the default behavior if you use the addEventListener method to handle an event. It only works when the event handler is declared as an element's attribute:
hyperlink.addEventListener('click', function (e) {
// Does NOT work
return false;
});
// Work
hyperlink.onclick = function (e) {
return false;
};
According to the HTML 5 specifications, return false will cancel the event except for the mouseover event.
Good practices
It's recommended to use the preventDefault method instead of return false inside an event handler. Because the latter only works with using the onclick attribute which will remove other handlers for the same event.
If you're using jQuery to manage the events, then you're able to use return false within the event handler:
$(element).on('click', function (e) {
return false;
});
Before returning the value of false, the handler would do something else. The problem is that if there's any runtime error occurring in the handler, we will not reach the return false statement at the end.
In that case, the default behavior will be taken:
$(element).on('click', function (e) {
// Do something here, but if there's an error at runtime
// ...
return false;
});
We can avoid this situation by using the preventDefault method before performing any custom handler:
$(element).on('click', function (e) {
e.preventDefault();
// Do something here
// The default behavior is prevented regardless of errors at runtime
// ...
});
Good to know
If you're using jQuery to manage the event, then return false will behave the same as the preventDefault() and stopPropagation() methods:
$(element).on('click', function (e) {
// Prevent the default event from happening and
// prevent the event from bubbling up to the parent element
return false;
});

Categories