Many times I\'ve seen links like these in HTML pages:
Click here !
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.
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);
}
I believe it causes the standard event to not happen.
In your example the browser will not attempt to go to #.
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.
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>
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.