I\'m trying to create a menu where the currently selected (clicked) element has a different background color than the other elements (I\'m trying to achieve this using JavaS
you need to use !important
on hover, basically it will increase its priority.
Try this,
p#links a:hover {
background-color: #f00 !important;
}
As Quentin said it looks like a dirty one, so in that situation we can make use of the class priority concepts.
HTML:
<a class='normal' href="#">Link 1</a>
<a class='normal' href="#">Link 1</a>
CSS:
.normal { background-color: blue; }
.abnormal{ background-color: yellow; }
.normal:hover { background-color: #f00; }
JS:
$('p#links a').attr('class', 'abnormal normal');
How about keeping the style in CSS and not in Javascript, by adding classes ?
so the line :
elements[i].style.backgroundColor = '#ff0';
Change to
elements[i].className = 'myClassForBackgrounds';
or in the jQ version
$('p#links a').css('background-color', '#ff0');
to :
$('p#links a').addClass('myClassForBackgrounds');
That way you can set your :hover
as you would normally
#links a:hover, .myClassForBackgrounds:hover { background-color:#ff0; }
The jQuery css()
method maps onto the style
property which maps onto the style
attribute.
Rules inside a style
attribute are more specific then rules in a stylesheet, so will always come after them in the cascade.
Instead of altering the CSS on the element directly, alter it by changing the classes the element belongs to and having a pre-prepared stylesheet.
Just for a more simple answer, in able to just re-enable css rules just have it toggle between the color and "", so
document.getElementById("id").style.backgroundColor = "rgb(255, 125, 15)";
would be if the element wasn't already colored via javascript. Now, if your element was already colored the code would look like this:
document.getElementById("id").style.backgroundColor = "";
That re-enables CSS so then your selectors will work.