The onclick attribute
<!DOCTYPE html> <html> <head> <title>What Color am I thinking about?</title> </head> <body> <p onclick="alert('Green');"> Click here to find out the colour I'm thinking of. </p> </body> </html>
We used single quotes (‘ ‘) around the argument we passed to our alert function. This is because we had already used double quotes to set the value of the onclick attribute. Always
use single quotes inside double quotes, or your code won’t run.
Using true and false with the return statement
RESERVED WORDS are words that cannot be used as function or variable names. This is because they are special commands that your browser understands. You don’t need to put reserved words in double quotes (“”)
The onclick attribute and hyperlinks
<body> <a href="mynewpage.html"> Click here to visit my new web page </a> </body>
Then you add the onclick attribute and the return statement. Set the value of the return statement to “false“, like this:
<body> <a href="mynewpage.html" onclick="return false;"> Click here to visit my new web page </a> </body>
Using “false“ as the value of our onclick means that nothing will happen when the user clicks on the link.
1) Open up your text-editing program. Create a new HTML file called onclick.html. Type this code into your new file:
<!DOCTYPE html> <html> <head> <title>Onclick</title> </head> <body> </body> </html>
2) In your < body > create a hyperlink that will take your user to Google. Use the anchor < a > tag and href attribute. Set the value to the Google URL. Your code will look like this:
<body> <a href="https://www.google.com"> Google </a> </body>
<a href="https://www.google.com" onclick="alert('Redirecting to Google');"> Google </a>
4) Save your HTML file and open it in your browser. When you click on the link an alert will pop up. When you click OK, you will be taken to Google.
5) Now stop your hyperlink from taking you to Google. Use a return statement in your onclick like this:
<a href="https://www.google.com" onclick="return false;"> Google </a>
Save your file and refresh your page. When you click on the link, your page won’t connect to Google.