Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

css hover event not working after using javascript?

Tags:

javascript

css

Here is the code in which i am having the problem-

<!DOCTYPE html>
<html>
<head>
<style type="text/css">
p {
    font-family: Tahoma;
    line-height: 170%;
    color: #000;
    font-size: 15px;
    padding: 5px 0px 5px 0px;
    text-align: center;
}
#col1 {
    //some propeties
}
#col1:hover ~ p {
    color: #f00;
}

#col2 {
    //some propeties
}
#col2:hover ~ p {
    color: #ff0;
}
</style>
</head>
<body>
<div id="col1"><span>Hover to view and click to select this color.</span></div>
<div id="col2"><span>Hover to view and click to select this color.</span></div>

<p>This is some text.</p>

<script type="text/javascript">

var pElements = document.getElementsByTagName("p");

$('#col1').click(function(){
for(var i = 0; i < pElements.length; i++) {
   pElements[i].style.color = "#f00";
}
});

$('#col2').click(function(){
for(var i = 0; i < pElements.length; i++) {
   pElements[i].style.color = "#ff0";
}
});

</script>
</body>
</html>

What i actually want is that when i hover a color div, the color of text in p tag changes for only that time when the color div is hovered. When the color div is clicked the color of text should change permanently.

The problem with is that once i click on 1 of the color divs to finalize it for p tag, and then after that the other color is hovered the color change doesnt take place. The color permanently changes on click as it should happen.

like image 997
sdnr1 Avatar asked Dec 28 '12 15:12

sdnr1


1 Answers

When you set the p elements style with pElements[i].style.color = "#f00"; you are setting a more specific style then the one applied by your hover. In CSS, the most specific style get's applied to the element. The CSS hover class you've got defined will never be applied because it is not specific enough to overwrite the inline styles applied by your javascript code.

You could modify your CSS hover class to use the !important tag, this should allow you to apply the hover style even though it is not as specific as the inline style.

#col2:hover ~ p {
    color: #ff0 !important;
}
like image 100
jeremysawesome Avatar answered Oct 04 '22 23:10

jeremysawesome