CSS and Javascript: a function for changing the style of pointing color effects

I have an element where I set the text color and a different text color for the hover state in CSS. I have javascript, so when I click on an element, it changes the color of the text of the element. It works great, except that it also affects the CSS slope, which I want to leave the same as the previously hover CSS. Is there anyway to either stop css freezing from execution, or set CSS slope?

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";}; 
+4
source share
4 answers

Instead of directly setting the color, it would be cleaner (and more efficient for using the class).

CSS:

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

JavaScript:

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

demonstration

+5
source

Use classes!

 #test {color: blue;} #test:hover, #test.foo:hover {color:green;} #test.foo { color : #cc0000 } 

Basic JavaScript:

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

Of course, you have to switch classes.

+1
source

The problem you are facing is the concept of specificity in css. Specificity controls which rules apply and in which order. Since javascript updates the style element, it overrides the specifics and erases all previous rules regarding the color style. so instead, add a class, for example, "clicked" on an element. where did your new color click

 .clicked{color:red} function change() {document.getElementById("test").class += " clicked"}; 

This will do what you need.

0
source

You can use !important JSFIDDLE

 #test:hover {color:green!important;} 
-1
source

Source: https://habr.com/ru/post/1479053/


All Articles