What's the effect of adding 'return false' to a click event listener?
Asked Answered
U

15

425

Many times I've seen links like these in HTML pages:

<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>

What's the effect of the return false in there?

Also, I don't usually see that in buttons.

Is this specified anywhere? In some spec in w3.org?

Underhung answered 24/9, 2008 at 18:28 Comment(2)
And the practical problem in leonel's example is that if the current page is scrolled down some way it will jump to top without the return false;Illustration
My IntelliJ complains on "return false;" with "outside function definition" messageBrainpan
A
359

The return value of an event handler determines whether or not the default browser behaviour should take place as well. In the case of clicking on links, this would be following the link, but the difference is most noticeable in form submit handlers, where you can cancel a form submission if the user has made a mistake entering the information.

I don't believe there is a W3C specification for this. All the ancient JavaScript interfaces like this have been given the nickname "DOM 0", and are mostly unspecified. You may have some luck reading old Netscape 2 documentation.

The modern way of achieving this effect is to call event.preventDefault(), and this is specified in the DOM 2 Events specification.

Affected answered 24/9, 2008 at 18:36 Comment(6)
event.preventDefault ? event.preventDefault() : event.returnValue = false; will work in IE tooLiuka
Every browser except Chrome worked with the return false method, but I needed event.preventDefault for Chrome.Aldon
Chrome works with the return false method now. It stops following the link in the onclick event of an img element.Faceoff
In plain JS form submit handler returning false isn't working (at least in Chrome) so I use e.preventDefault(). according to @ 2astalavista 's comment above e.preventDefault fails in IE so use his method: event.preventDefault ? event.preventDefault() : event.returnValue = false;Burkhart
"I don't believe there is a W3C specification for this" Actually, there is (see step 5 -> Otherwise)Cinema
W3C may have a spec for this, but I can't find this behavior in MDN's addEventListener doc.Foreshank
L
183

You can see the difference with the following example:

<a href="http://www.google.co.uk/" onclick="return (confirm('Follow this link?'))">Google</a>

Clicking "Okay" returns true, and the link is followed. Clicking "Cancel" returns false and doesn't follow the link. If javascript is disabled the link is followed normally.

Locarno answered 25/9, 2008 at 9:52 Comment(1)
Exactly what i was looking for, works also perfect on submit buttons! <button type="submit" onclick="return confirm('Do you really want to delete this?');">Delete</button>Dentistry
J
32

WHAT "return false" IS REALLY DOING?

return false is actually doing three very separate things when you call it:

  1. event.preventDefault();
  2. event.stopPropagation();
  3. Stops callback execution and returns immediately when called.

See jquery-events-stop-misusing-return-false for more information.

For example :

while clicking this link, return false will cancel the default behaviour of the browser.

<a href='#' onclick='someFunc(3.1415926); return false;'>Click here !</a>
Juarez answered 19/8, 2014 at 7:26 Comment(4)
onclick="return false" is not the same as returning false from a jQuery click event handler. Browsers only prevent the default handler (e.g e.preventDefault()) but do not stop propagation. See: jsfiddle.net/18yq1783Licking
Fwiw, the link to the blog is broken atm. An archive is here.Norward
Here's a link to the blog post that works, at least at present.Turn
return false isn't "doing those things when you call it", though (also return isn't reallay something that is "called"; it's not a function). return false just returns false. The browser does those things when it calls the click handler and gets a return value of false from it.Pattiepattin
K
30

Here's a more robust routine to cancel default behavior and event bubbling in all browsers:

// Prevents event bubble up or any usage after this is called.
eventCancel = function (e)
{
    if (!e)
        if (window.event) e = window.event;
        else return;
    if (e.cancelBubble != null) e.cancelBubble = true;
    if (e.stopPropagation) e.stopPropagation();
    if (e.preventDefault) e.preventDefault();
    if (window.event) e.returnValue = false;
    if (e.cancel != null) e.cancel = true;
}

An example of how this would be used in an event handler:

// Handles the click event for each tab
Tabstrip.tabstripLinkElement_click = function (evt, context) 
{
    // Find the tabStrip element (we know it's the parent element of this link)
    var tabstripElement = this.parentNode;
    Tabstrip.showTabByLink(tabstripElement, this);
    return eventCancel(evt);
}
Knotgrass answered 24/9, 2008 at 19:59 Comment(3)
A shim is nice, but what's the practical advantage over return false;? kamesh's answer deals with this a little, but since there's a chance your shim does one or the other, how are those separate outcomes going to make tabstripLinkElement_click change operation from browser to browser? If there's no operational difference, why (in practice) bother (even if, in theory, this is The Right Thing to do)? Thanks, and AIA for the zombie answer question.Norward
The first code block has a trailing else. Horrible coding style. Add in some curly braces so it's not ambiguous.Straitjacket
@DonaldDuck Are you sure about that whitespace? If I try if (false) if (true) console.log('true'); else console.log('false1'); I get undefined, not false1. If I add another line: if (false) if (true) console.log('true'); else console.log('false1'); else console.log('false2'); I get false2. That is, the else in else return belongs to if (window.event) I think.Norward
S
17

Retuning false from a JavaScript event usually cancels the "default" behavior - in the case of links, it tells the browser to not follow the link.

Sunnisunnite answered 24/9, 2008 at 18:30 Comment(1)
"usually"? so not always?Circumambulate
L
14

Return false will stop the hyperlink being followed after the javascript has run. This is useful for unobtrusive javascript that degrades gracefully - for example, you could have a thumbnail image that uses javascript to open a pop-up of the full-sized image. When javascript is turned off or the image is middle-clicked (opened in a new tab) this ignores the onClick event and just opens the image as a full-sized image normally.

If return false were not specified, the image would both launch the pop-up and open the image normally. Some people instead of using return false use javascript as the href attribute, but this means that when javascript is disabled the link will do nothing.

Locarno answered 24/9, 2008 at 18:33 Comment(0)
M
13

I believe it causes the standard event to not happen.

In your example the browser will not attempt to go to #.

Mara answered 24/9, 2008 at 18:30 Comment(0)
R
8

The return false is saying not to take the default action, which in the case of an <a href> is to follow the link. When you return false to the onclick, then the href will be ignored.

Roughspoken answered 24/9, 2008 at 18:31 Comment(0)
B
8

using return false in an onclick event stops the browser from processing the rest of the execution stack, which includes following the link in the href attribute.

In other words, adding return false stops the href from working. In your example, this is exactly what you want.

In buttons, it's not necessary because onclick is all it will ever execute -- there is no href to process and go to.

Bizet answered 24/9, 2008 at 18:31 Comment(0)
S
5

I am surprised that no one mentioned onmousedown instead of onclick. The

onclick='return false'

does not catch the browser's default behaviour resulting in (sometimes unwanted) text selection occurring for mousedown but

onmousedown='return false'

does.

In other words, when I click on a button, its text sometimes becomes accidentally selected changing the look of the button, that may be unwanted. That is the default behaviour that we are trying to prevent here. However, the mousedown event is registered before click, so if you only prevent that behaviour inside your click handler, it will not affect the unwanted selection arising from the mousedown event. So the text still gets selected. However, preventing default for the mousedown event will do the job.

See also event.preventDefault() vs. return false

Santos answered 8/3, 2014 at 14:59 Comment(1)
@FrederikKrautwald You are right, it was cryptic and I should have said 'selecting' not 'marking'. I've tried to write it more clear, hope it makes more sense.Santos
M
4

Return false will prevent navigation. Otherwise, the location would become the return value of someFunc

Mali answered 24/9, 2008 at 18:30 Comment(2)
no, the location would become the contents of the href attributeDurr
The location only becomes the return value of someFunc if it is href="javascript:someFunc()", this is not the case for event handlers.Affected
R
4

The return false prevents the page from being navigated and unwanted scrolling of a window to the top or bottom.

onclick="return false"
Reprobative answered 30/3, 2016 at 17:13 Comment(0)
T
3

I have this link on my HTML-page:

<a href = "" 
onclick = "setBodyHtml ('new content'); return false; "
> click here </a>

The function setBodyHtml() is defined as:

function setBodyHtml (s)
{ document.body.innerHTML = s;
}

When I click the link the link disappears and the text shown in the browser changes to "new content".

But if I remove the "false" from my link, clicking the link does (seemingly) nothing. Why is that?

It is because if I don't return false the default behavior of clicking the link and displaying its target-page happens, is not canceled. BUT, here the href of the hyperlink is "" so it links back to the SAME current page. So the page is effectively just refreshed and seemingly nothing happens.

In the background the function setBodyHtml() still does get executed. It assigns its argument to body.innerHTML. But because the page is immediately refreshed/reloaded the modified body-content does not stay visible for more than a few milliseconds perhaps, so I will not see it.

This example shows why it is sometimes USEFUL to use "return false".

I do want to assign SOME href to the link, so that it shows as a link, as underlined text. But I don't want the click to the link to effectively just reload the page. I want that default navigation=behavior to be canceled and whatever side-effects are caused by calling my function to take and stay in effect. Therefore I must "return false".

The example above is something you would quickly try out during development. For production you would more likely assign a click-handler in JavaScript and call preventDefault() instead. But for a quick try-it-out the "return false" above does the trick.

Tonisha answered 23/11, 2019 at 19:35 Comment(0)
K
2

When using forms,we can use 'return false' to prevent submitting.

function checkForm() {
    // return true to submit, return false to prevent submitting
}
<form onsubmit="return checkForm()">
    ...
</form>
Kazmirci answered 20/12, 2019 at 2:53 Comment(0)
S
1

By default, when you click on the button, the form would be sent to server no matter what value you have input.

However, this behavior is not quite appropriate for most cases because we may want to do some checking before sending it to server.

So, when the listener received "false", the submitting would be cancelled. Basically, it is for the purpose to do some checking on front end.

Selfforgetful answered 19/11, 2020 at 3:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.