Javascript link click event

onclick Event

The onclick event occurs when the user clicks on an HTML element.

Mouse Events

Event Occurs When
onclick The user clicks on an element
oncontextmenu The user right-clicks on an element
ondblclick The user double-clicks on an element
onmousedown A mouse button is pressed over an element
onmouseenter The pointer is moved onto an element
onmouseleave The pointer is moved out of an element
onmousemove The pointer is moving over an element
onmouseout The mouse pointer moves out of an element
onmouseover The mouse pointer is moved over an element
onmouseup The mouse button is released over an element

See Also:

Tutorial:

Syntax

In JavaScript, using the addEventListener() method:

Technical Details

Bubbles: Yes
Cancelable: Yes
Event type: MouseEvent
Supported
HTML tags:
All exept: , ,
, , , , , , , , and

More Examples

Click a to display the date:

Click a element to change the text color:

Click me to change my color.

Another example on how to change the color of an element:

Click me to change my color.

Click to copy text from one input field to another:

function myFunction() document.getElementById(«field2»).value = document.getElementById(«field1»).value;
>

How to assign an «onclick» event to the window object:

function myFunction() document.getElementsByTagName(«BODY»)[0].style.backgroundColor = «yellow»;
>

Use onclick to create a dropdown:

function myFunction() document.getElementById(«myDropdown»).classList.toggle(«show»);
>

Browser Support

onclick is a DOM Level 2 (2001) feature.

It is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes 9-11

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Learn how to get the href attribute of any, or specific, clicked links in JavaScript.

When the user clicks on a link in your HTML document, you want to retrieve the target URL, meaning the value of the href attribute, with JavaScript.

What is the best way to accomplish this?

To get the value of the href attribute of a clicked link, create an event listener using AddEventListener() and retrieve the value of the href attribute using Element.target() .

This tutorial will show you exactly how to do this in two steps.

First, you will learn how to create an event listener for all links or for specific links. Second, you will learn how to retrieve the value of the href attribute of a link when the user clicks it.

Creating an Event Listener

The EventTarget.AddEventListener() method of the EventTarget() Web API in JavaScript lets you create event listeners for when the user clicks on a DOM element in your HTML document.

This method lets you declare a function that gets called every time the event is fired. From the event, you can read the properties of the DOM element that it was attached to, allowing you to parse the value of the href attribute and store it in a variable.

The syntax for the AddEventListener() method is as follows:

// Event listener syntax EventTarget.AddEventListener(type, listener);

Both the type and the listener arguments are mandatory.

Type is a string that specifies the event type that you want the event listener to listen for.

Listener can be an object within the scope of the EventListener Web API, or a function that gets called every time the event is fired.

In this case, we need to create an event listener for clicks on link elements, meaning elements.

One of the best ways to do this is to use the Document.querySelectorAll() method. This method lets you create a loop that targets all instances of specific DOM elements using CSS selectors.

So you can do a simple selection for all links on your HTML page—or a narrowed-down selection of links with a specific id, class, or other.

Here’s how an event listener for all link clicks looks like:

// Create event listener for all link clicks document.querySelectorAll('a').forEach(link =>   link.addEventListener('click', (e) =>   console.log('A link was clicked');  >); >);

If you need to narrow down your event listener’s scope to clicks on specific links, for example links with a given id or className , all you need to do is modify your CSS selector:

// Event listener only for document.querySelectorAll('a.nav-item').forEach(link =>   link.addEventListener('click', (e) =>   console.log('A link was clicked');  >); >); // Event listener only for document.querySelectorAll('a#nav-item-01').forEach(link =>   link.addEventListener('click', (e) =>   console.log('A link was clicked');  >); >);

Depending on your implementation requirements, a CSS selector can be as simple as targeting elements or as complex as targeting an n-th element within a parent element or a group of elements.

Mastering CSS selectors can take your query selection skills to the next level. If you’re a frontend developer, this skill will give you an upper hand in your daily work.

Retrieving the Href Attribute

Now that you know how to create event listeners that listen to clicks on links, whether all links or specific links, let’s look at how to retrieve the value of the href attribute from them.

This can be done by passing on the e parameter to the function,short for “event,” that gets called on click.

Then, you can use the Event.target() Web API to retrieve the className attribute of the DOM object to which the event in your event listener was attached:

// Create event listener for all link clicks document.querySelectorAll('a').forEach(link =>   link.addEventListener('click', (e) =>  // Retrieve href and store in targetUrl variable let targetUrl = e.target.href; // Output value of targetUrl to console  console.log('A link with target URL ' + targetUrl + 'was clicked');  >); >);

If you opened up your browser’s console right now, copy/pasted and ran this code, then clicked on a link or two, you’d observe the following results:

In Conclusion

I hope you found this tutorial useful.

I recently had to tackle this challenge myself as I implemented a data layer for analytics purposes on one of my websites. It took me a few tries (and a couple of hours) to get to the best solution, and I believe this is it.

If you have any questions, or you want to share other ways to achieve this with the rest of this post’s readers, be sure to leave a reply below.

1 comment

Greetings.
Just what I needed after several hours of trying with a multilevel menu. Excellent tutorial. Thank you very much, very grateful.

Leave a comment Cancel reply

  • How to Wait for an Element to Exist in JavaScript July 13, 2023
  • How to Check If a Function Exists in JavaScript July 13, 2023
  • How to Remove Numbers From a String With RegEx July 13, 2023
  • How to Check If a String Is a Number in JavaScript July 13, 2023
  • How to Insert a Variable Into a String in PHP July 12, 2023

We publish growth advice, technology how-to’s, and reviews of the best products for entrepreneurs, creators, and creatives who want to write their own story.

Maker’s Aid is a participant in the Amazon Associates, Impact.com, and ShareASale affiliate advertising programs.

These programs provide means for websites to earn commissions by linking to products. As a member, we earn commissions on qualified purchases made through our links.

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

Читайте также:  Тег MARQUEE
Оцените статью