Why does the
return false precedence over, for example, an href?
We have this code as an example:
<!DOCTYPE html> <html> <head> <title>Uma página linda</title> </head> <body> <a href="http://stackoverflow.com/" onclick="return false;" title="Link pra stackoverflow" target="_blank">Melhor site de todos (Stackoverflow)</a> </body> </html>
When clicked, in this case nothing would happen due to the
return false .
But why that?
Why when clicking on the link the website's targeting event doesn't "work"?
It is not a question of prevailing. What happens when you click on the link is that it is triggered in an event. This event just calls a code that must execute what the programmer wants. In this case, the event is called
onclick and is associated with
a href . The code can do what it wants there. In this case he doesn't do anything.
It was defined in the specification (I believe) that this code would define whether or not the normal click action would still be performed based on the return of a boolean provided by this code executed by the event. So if the code returns
true (if I'm not mistaken it doesn't need to return something specific for the normal action to occur) the normal action is still executed after the action of this code, but returning
false the normal action is suppressed. It is assumed that everything that should be done is already done by the code.
It's a useful convention set up to give you more flexibility. It's just a simple decision made by the engine based on pre-established rules. Imagine how difficult it would be to perform certain tasks if the link always "worked" after you did an action. Eventually you would have repeated action or conflicting actions.
<a href="http://www.pt.stackoverflow.com/" onclick="return (confirm('Pode seguir o link?'))">SOpt</a>
Today it is possible to use something more modern like event.preventDefault .