Execute Javascript using HTML hyperlink

One of the way to dynamically execute Javascript codes is by using hyperlink. The trick is to use a URL starting with javascript: , followed by the Javascript code itself.

The URL can be in image, link, or CSS style, and in the example below an alert will pop up when the link is clicked;

<a href="javascript:window.alert('Red Alert')">
Click here

Sign up for The Complete JavaScript Course: Build Real Projects! and many other great courses on Udemy to learn more.

Written by Mohd Shakir Zakaria. Last updated on 2019-02-12