3

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.

4
  • 1
    Can you share the code snippets on code pen or provide the whole HTML, CSS, and JS codes. Commented Oct 6, 2020 at 20:34
  • Err my javascript is filled with interactions with server data so that gets a little complicated. I'm just checking to see if there's a javascript method that exists already that can handle this like tag.style.color. Commented Oct 6, 2020 at 20:45
  • Try document.getElementById("myDIV").classList.add("mystyle"); w3schools.com/jsref/prop_element_classlist.asp or toggle instead of add Commented Oct 6, 2020 at 20:50
  • It seemed promising, but this would only work after the button is clicked and I only want the color to be changed while it's active. Before it's fully clicked. Commented Oct 6, 2020 at 21:02

2 Answers 2

2

You can set an ID on the link and target that with the css

#my-id {color: blue}
#my-id:active {color: red}
Sign up to request clarification or add additional context in comments.

Comments

2

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';
  });

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.