Given a link with onclick() event and return statement and the task is to get the effect after clicking the event. Below is a code containing anchor element, onclick() event, and return statement.
<a href='https://www.google.com' onclick='someFunc(3); return false;'> Click here ! </a>
What is the effect of the return false to a click event listener?
Explanation: Have you ever come across pop up alerts on websites asking for permission for a task/redirection? Those pop-ups have two choices yes or no. If there is a return false statement then there in an event listener for that alert message, it may correspond to not executing the default set of instructions .
The return value of the event handler is used to determine if the default (desired) browser behavior should take place or not.
Example: The following JavaScript code (tobrdeleted.js), which prints the number plus 1.
Javascript
function someFunc(n) { console.log(n + 1); } |
Let’s say we invoke the above function using the following HTML code.
HTML
<!DOCTYPE html> < html > < head > < script src = "tobrdeleted.js" ></ script > </ head > < body > onclick = 'someFunc(3); return true;' > Click here ! </ a > </ body > </ html > |
When we write return true; then on click of “Click here !” takes us to the target page (in our case, www.geeksforgeeks.org) and the function someFunc(3) is not called.
HTML
<!DOCTYPE html> < html > < head > < script src = "tobrdeleted.js" ></ script > </ head > < body > onclick = 'someFunc(3); return false;' > Click here ! </ a > </ body > </ html > |
When we write return false; then on click of “Click here !” does not redirect to anywhere. Instead, it executes the function someFunc(3).