Why return false after location.reload() using onclick?

Viewed 1837

I'm making a JavaScript app where I use the method location.reload(). The method location.reload() is in a onclick event handler to reset the page, and this answer says that you need to return false; after location.reload() with onclick : How to reload a page using JavaScript.

location.reload();

See this MDN page for more information.

If you are refreshing after an onclick then you'll need to return false directly after

location.reload();
return false;

Why should you return false; after method location.reload() using onclick?

1 Answers

If the event listener is attached to a link, then clicking the link will result in going to another page instead of reloading the page. return false will prevent the default action in an inline event handler and the onclick property.

Without return false:

document.querySelector('a').onclick = function() {
  location.reload();
}
<a href="https://www.example.com">Click</a>

With return false:

console.log('Loaded', new Date);
document.querySelector('a').onclick = function() {
  location.reload();
  return false;
}
<a href="https://www.example.com">Click</a>

In modern JavaScript, addEventListener and event.preventDefault() would be used instead.

document.querySelector('a').addEventListener('click', function(e){
    e.preventDefault();
    location.reload();
});
Related