Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CSS and Javascript: Function to change color effects hover style

I have an element where I set a text color and a different text color for the hover state in the CSS. I have some javascript so that when I click the element, it changes the text color of the element. It works fine except that it also effects the hover CSS which I want to remain the same as the pre-clicked hover CSS. Is there anyway to either stop the hover css from being effected or to set the hover CSS?

http://jsfiddle.net/77zg8/

CSS:

#test {color: blue;}
#test:hover {color:green;}

HTML:

<div id="test" onClick="javascript:change()">qwerty</div>

Javascript:

function change() {document.getElementById("test").style.color="#cc0000";};
like image 856
user2219915 Avatar asked Mar 24 '23 02:03

user2219915


1 Answers

Instead of setting the color directly, it would be cleaner (and more effective to use a class).

CSS :

#test {color: blue;}
#test.active {color:red;}
#test:hover {color:green;}

JavaScript :

function change() {
   document.getElementById("test").className='active';
}

demonstration

like image 150
Denys Séguret Avatar answered Apr 10 '23 08:04

Denys Séguret