skip to Main Content

Forgive me for my silly question, I’m a beginner :/
For some reason, I can’t use Jquery due to some stuff with Divi theme on WordPress.

I need to change CSS class to some links so that they will change color if selected
(these links reveals different divs contents)

I’ve tried this:

function linkcolor() {
   document.getElementById(arguments[0]).className='serveminus'; 
   for(var i=1; i< arguments.length-1; i++) {
      document.getElementById(arguments[i]).className='serve'; 
   }  
}

When I call the function I’ll add the anchors’ ids as parameters.
The first one will be shown as “selected” (serveminus) one while the other will be grayed out (serve).
Somehow I’ve got this working but I need to have this other feature:
When a link is already selected and it has the “serveminus” class, if clicked again, the class changes back to “serve”.

If I add the following condition I guess it generates a nonsense loop….

 if (document.getElementById(arguments[0]).className='serveminus') {
    document.getElementById(idlink).className='serve';
 } else {

2

Answers


  1. Sounds like you need to set an onClick event listener:
    https://developer.mozilla.org/en-US/docs/Web/API/EventListener

    Pseudo code might be:

    if link is clicked and link is selected
      set event listener on link 
        onClick change class to 'serve'
        remove event listener
    
    Login or Signup to reply.
  2. Sounds like you need an eventListener that will toggle the class, I would first have all the links that you want to apply this style to in an variable. And apply the code block below .

    var linkArray = doucument.querySelectorAll('navigationLinks');
    // Example-> var linkArray = document.querySelectorAll('nav ul li a');
    
    for(var i = 0; i < linkArray.length; i++) {
      linkArray[i].addEventListener("click", e => {
        e.target.classList.toggle('classToToggle');
      })
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search