JavaScript Hyperlink onclick | Add onClick event Example code

How to make this a tag working with href and onClick?

The default behavior of the <a> tag’s onclick and href properties is to execute the onclick, then follow the href as long as the onclick doesn’t return false, canceling the event (or the event hasn’t been prevented).

Example of code make this a tag working with href and onClick (Add onclick event to hyperlink):-

Output:

Examples of JavaScript hyperlink onclick

Here are many ways to do put onClick function on hyperlink JS.

Bad:

Good:

Better:

Even better 1:

Even better 2:

Why better? because return false will prevent browser from following the link

Use jQuery or other similar framework to attach onclick handler by element’s ID.

Source: stackoverflow.com

Do comment if you have any doubts and suggestions on tutorial.

Note: The All HTML Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.