Open In App

How to Change Link Color onClick and Keep It using JavaScript?

Last Updated : 14 Nov, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

To change the color of a link on click and keep it that way using JavaScript, you can modify its style or apply a CSS class. Here's how you can achieve this:

Example: Changing Link Color on Click and Keeping It

HTML Structure

HTML
<a href="#" class="link" id="myLink">Click me</a>

<style>
  .active-link {
    color: red; /* Change this to your desired color */
  }
</style>

<script>
  document.getElementById('myLink').addEventListener('click', function(event) {
    event.preventDefault(); // Prevent default behavior if needed

    // Remove the active-link class from all links if you want only one to be active
    const links = document.querySelectorAll('.link');
    links.forEach(link => link.classList.remove('active-link'));

    // Add the active-link class to the clicked link
    this.classList.add('active-link');
  });
</script>

Output:

Screenshot-2024-11-14-132720
Output
Screenshot-2024-11-14-132729
On Clicking the Link

Explanation:

  1. HTML Structure:
    • A simple <a> tag with an id and class. The class="link" is used to group multiple links if needed.
  2. CSS Class for Active State:
    • .active-link sets the desired color for the clicked link. You can customize the color as per your requirement.
  3. JavaScript Logic:
    • An event listener is attached to the link. When the link is clicked, the active-link class is added to it.
    • event.preventDefault() prevents the default link behavior (navigation) if necessary.
    • To ensure only one link remains active, you can first remove the active-link class from all links and then add it to the clicked link.

Handling Multiple Links

If you have multiple links and want to keep track of which one was last clicked, you can use a similar approach by applying the event listener to all links with a common class:

HTML
<a href="#" class="link">Link 1</a>
<a href="#" class="link">Link 2</a>
<a href="#" class="link">Link 3</a>

<script>
  document.querySelectorAll('.link').forEach(link => {
    link.addEventListener('click', function(event) {
      event.preventDefault(); // Prevent default behavior if needed

      // Remove the active-link class from all links
      document.querySelectorAll('.link').forEach(link => link.classList.remove('active-link'));

      // Add the active-link class to the clicked link
      this.classList.add('active-link');
    });
  });
</script>

Output:

Screenshot-2024-11-14-132943
Output


Summary:

  • The active-link class is used to change and persist the color.
  • The addEventListener() method handles clicks on links.
  • To handle multiple links, loop through all elements and manage the class application accordingly.
  • This approach ensures that the clicked link keeps its new color until another link is clicked

Next Article

Similar Reads