html

How to Include Both href and onclick to HTML <a> Tag

HTML permits its user to add various attributes inside the HTML elements. Furthermore, it also allows the developers to invoke the JavaScript function inside the HTML elements to make the website more responsive. For instance, you may need to capture the click event and then navigate to another website. To do so, the “href” and “onclick” are both attributes in the HTML “<a>” tag.

This post explains for including the onclick and href both to HTML <a> tag.

How to Include Both “href” and “onclick” to HTML “<a>” Tag?

To include both href and onclick to HTML <a> tag, create a div container, and insert the “<a>” tag. Then, in between the “<a>” tag, use the “href” html attribute and the “onclick” JavaScript event.

To do so, follow the given instructions.

Step 1: Create a div Container

First, create a div container by utilizing the “<div>” tag.

Step 2: Add Both “href” and “onclick in a Tag

Next, use the “<a>” tag and insert the “href” attribute to add the URL of the website and the “onclick” attribute to perform an event when the user clicks on it:

<div>
 <a href="https://linuxhint.com/" onclick="create(event)">Click Me</a>
</div>

As a result, when the added link is clicked, an event will be created, and we are navigated to the “Linux hint” homepage:

Step 3: Use “alert()” Function

Add the “<script>” tag and insert the following function in between the script:

<script>
 function create(e) {
 alert("Hello");
}
</script>

According to the given code:

  • The “function create(e)” is defined for creating a new event when a user clicks on the stated link embedded in the text.
  • alert()” function generates an alert message when a user clicks on the link. Users must confirm by clicking on “OK” to move ahead.

As a result, clicking the button will open up an alert box with the message “Hello”:

The given functionality can be utilized in scenarios like displaying a message in case of successful sign-up on a website.

 Step 4: Apply “e.preventDefault()” Function

In the opposite case, when the “e.preventDefault()” function is invoked, it will stop creating an event while the user clicks on the embedded link:

function create(e) {
 e.preventDefault();
}

 

As a result, nothing will happen after the click:

That’s all about including the href and onclick inside the <a> tag of HTML.

Conclusion

To include the href and onclick to the HTML “<a>” tag, first, create a “div” container and insert the “<a>” tag in HTML. Then, add the “href” for inserting the URL of the website. After that, add an “onclick” event which is utilized for creating an event when the user clicks on the link. This article has explained the method for adding href and onclick in an HTML tag.

About the author

Hafsa Javed