Reputation: 666
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?
Upvotes: 0
Views: 293
Reputation: 198
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
Upvotes: 0
Reputation: 2509
function changeClass()
{
var element = document.getElementById('home');
element.className += 'topMenuon';
}
<li><a id="home" onclick="changeClass();" href="#">Home</a></li>
Upvotes: 0
Reputation: 2235
Apply as
var element = document.getElementById('home');
element.setAttribute("className", newClass);
Upvotes: 0
Reputation: 9174
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).
Upvotes: 0
Reputation: 1514
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!
Upvotes: 1
Reputation: 164
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';
};
Upvotes: 1