How to make a JavaScript hyperlink

Learn how to create a hyperlink in JavaScript using HTML anchor tags & JavaScript functions, complete with an example.

Creating a JavaScript Hyperlink

Creating a JavaScript hyperlink is quite simple. All you need to do is include an HTML <a> tag in your document, with a "href" attribute that contains the link address. You can also include an "onclick" attribute with a JavaScript function call, to be executed when the link is clicked.


<a href="https://example.com" onclick="someFunction();">Click Me!</a>

The "href" attribute is required for the link to work, and should contain the URL you want the link to point to. The "onclick" attribute is optional, but can be used to execute a JavaScript function when the link is clicked. For example, you could have a function that opens an alert window, or changes some content on the page.


// Opens an alert window
function someFunction() {
  alert("You clicked the link!");
}

In the example above, the "onclick" attribute is set to "someFunction();", which means that the "someFunction" function will be executed when the link is clicked. You can also use the "onclick" attribute to call multiple functions, by separating each function call with a comma.


<a href="https://example.com" onclick="someFunction(), someOtherFunction();">Click Me!</a>

Once you have the HTML tag and JavaScript function in place, you should have a working JavaScript hyperlink. You can also use the "onmouseover" and "onmouseout" attributes to call JavaScript functions when the user hovers over or leaves the link.

Answers (0)