Reputation: 159
I'm trying to add in a bunch of <p<a/a>/p> elements with javascript and wanted to change the active color of a link with javascript. How would I do that? I can't change the color of all hyperlinks with a:active on the css file because I have a set of other links that I want a different color that I'm currently using css to solve.
These are my additions through javascript:
var supertag = document.createElement("p");
var tag = document.createElement('a');
var text = document.createTextNode("Join a New Community!");
tag.appendChild(text);
tag.href = "http://localhost:8088/communities_index/communities_index.html";
tag.style.color = "blue";
supertag.appendChild(tag);
var element = document.getElementById("globalCommunities");
element.appendChild(tag);
I can change the hyperlink's color to blue but then it loses its active color which would've been red to css. The other links are black which then turn blue on hover and red on active. I'd like the new hyperlink to be blue and turn red when active.
Upvotes: 3
Views: 1673
Reputation: 21
Seems like there's no programmatic way to target the CSS :active
state in JavaScript. One approach would be to listen for mouseup and mousedown events on the links in question and set their color via style.
// Grab your link, here an element with ID my-link
var a = document.querySelector('#my-link');
// Set mousedown event listener
a.addEventListener('mousedown', () => {
// Use style to set element color
a.style.color = 'red';
});
// Set mouseup event listener
a.addEventListener('mouseup', () => {
// Use style to set element color
a.style.color = 'blue';
});
Upvotes: 2
Reputation: 520
You can set an ID on the link and target that with the css
#my-id {color: blue}
#my-id:active {color: red}
Upvotes: 2