Home » Jquery » javascript – How to change color of options in list onclick-Exceptionshub

javascript – How to change color of options in list onclick-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

My HTML code:

<li onclick="switchColors()">
    <a class="x" href="Faculty.php">Faculty</a>
 </li>
<li onclick="switchColors()">
   <a class="x" href="Contact.php">Contact</a>
</li>

JavaScript Code:

<script>
  function switchColors(element)  
  {  
    links=document.getElementsByTagName("li") ;  
    for (var i = 0 ; i < links.length ; i ++)  
    links.item(i).style.color = 'orange' ;  
     element.style.color='purple' ;  
   } 
</script>

What i want to do is that when i click on “Faculty” it loads Faculty.php page and change “Faculty” color into purple and “Faculty” remains in purple untill i click on “Contact”. And when i click on “Contact” it load Contact.php page and change “Contact” color into purple, and also set “Faculty” to orange color.

I tried the above JS code but it don’t work, when i click on “Faculty” it load Facult.php page but don’t change “Faculty” into purple color.

How should i do that?

How to&Answer:

this doesn’t work with javascript “onClick” event. because your page refreshes.

you need to set a variable in your PHP and set the page name to that. and then have an “if” in PHP to declare which page you are then set class for your “li” element to change its color.

A guide is in link below:

https://alistapart.com/article/keepingcurrent/