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
<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:


Explanation:
- HTML Structure:
- A simple
<a>tag with anidand class. Theclass="link"is used to group multiple links if needed.
- A simple
- CSS Class for Active State:
.active-linksets the desired color for the clicked link. You can customize the color as per your requirement.
- JavaScript Logic:
- An event listener is attached to the link. When the link is clicked, the
active-linkclass 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-linkclass from all links and then add it to the clicked link.
- An event listener is attached to the link. When the link is clicked, the
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:
<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:

Summary:
- The
active-linkclass 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