简体   繁体   中英

Setting CSS color with javascript onclick

Hi i am trying to make my menu link go red when i am on that page and its not working.

Html:

<li><a id="home" onclick="changeClass('home')" href="index.php">Home</a></li>

CSS:

#topMenu li{
    display:inline;
    margin-right:60px;
    font-size:12px;
    font-weight:bold;
    color:#000;
    text-decoration:none;
    }

#topMenu li a{
    color:#000;
    text-decoration:none;
    }

#topMenu li a:hover{
    color:#666;
    text-decoration:underline;
    }

.topMenuon{
    color:#F00
    }

Javascript:

 function changeClass(id)
    {
       var element = document.getElementById(id);
       element.className = element.className + ”topMenuon”;

    } 

Any ideas on how i could get this to work?

It's simpler to Include Jquery, and do this:

$('#home').on('click',function(){

   $(this).addClass('topmenuon');

});

However, it won't work like that if you are going to another page. You must detect what page you are on somehow in javascript/jquery (using something in the url, or using identifier on the page such as the section title), and then add your class while you are on that page (or,do it server side and don't call it at all if server renders directly). Can't use onclick like that if you're leaving the page anyway, new page has no way of knowing if you are doing full postback rather than ajax!

You might want to do that server side, but if for some reason you cannot and you cannot use jQuery :

function changeClass (id) {
  var el = document.getElementById(id);
  if (el.href == location.pathname) el.className += 'topMenuon';
};

use jquery - this in the <head> ...

 <script src="yourPath/jquery_1.8.0_min.js" type="text/javascript"></script>

then...

 $(document).ready(function(){

   $("#home").addClass('topMenuon');

 }

that'll do it...

S

Plain js

window.onload = function(){
   document.getElementById("home").onclick = function(){
      this.className +=" topMenuon" ;
   }
}

Edit

You are probably going to a new page on the click of the link. Hence the above code would not change the class of the link since you are now on a new page.

You may need to add the class to the link using php(i assume you are using it).

Apply as

var element = document.getElementById('home');  
        element.setAttribute("className", newClass);
function changeClass()
        {
            var element = document.getElementById('home');
            element.className += 'topMenuon';
        } 


<li><a id="home" onclick="changeClass();" href="#">Home</a></li>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM