3

Css "hover" selector applys a temporary style to an element, but it isn't definitive:

div:hover {
 background-color: red;
}

I can do the same thing with javascript but it is a bit complicate and impossible for several elements:

var elem = document.getElementsByTagName ("div")[0];

elem.onmouseover = function () {
 this.style.backgroundColor = "red";
}

elem.onmouseout = function () {
 this.style.backgroundColor = "transparent";
}

Is there a better way ? Something like this:

document.getElementsByTagName ("div")[0].ontemporarymouseover = function () { // LoL
 this.style.backgroundColor = "red";
}

Thanks

Caio
  • 3,178
  • 6
  • 37
  • 52
  • 1
    What does "isn't definitive" mean in this context? – Quentin May 16 '10 at 15:39
  • 2
    Function `getElementByTagName` does not exist. There is only `getElementsByTagName`. It must be a reason of the issue you have. – MiKo May 16 '10 at 15:45
  • Further to my previous comment, my gut says you are trying to use JavaScript to hack around a lack of understanding of the cascade: http://www.w3.org/TR/CSS21/cascade.html#specificity – Quentin May 16 '10 at 15:54

4 Answers4

2

No, there is no way to apply styles that go away by themselves.

Eventhough the CSS contains only one definition, it actually corresponds to the two state changes that triggers onmouseover and onmouseout. When the pointer enters the element, the :hover pseudo class is added to it making the CSS rule apply. When the pointer leaves the element, the :hover pseudo class is removed making the CSS rule no longer apply.

Guffa
  • 687,336
  • 108
  • 737
  • 1,005
1

In JavaScript this behaviour can only be handled by listening to the mouseover and mouseout DOM events, as you did in your second example. However it is recommended to handle hovering styles with CSS, as in your first example.

Daniel Vassallo
  • 337,827
  • 72
  • 505
  • 443
0

I believe that if you use the jQuery JavaScript framework, you can do this:

$('div:first').hover(function(){
   $(this).css('background-color','red');
},function(){
   $(this).css('background-color','white');
});
james_womack
  • 10,028
  • 6
  • 55
  • 74
0

// jQuery 'Temporary mouseevents'

$("element").bind
({
    mouseover:
        function ()
        {
        },
    mouseout:
        function ()
        {
        }
});

$("element").unbind('mouseover mouseout');

I hope this is a good approach for what you need.

BrunoLM
  • 97,872
  • 84
  • 296
  • 452