views:

63

answers:

4

Hi guys :)

Css "hover" selector applys a temporary style to an element, 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

+1  A: 

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
You can use the Javascript to set (and unset) a "hover" class, and then apply styles with CSS.
Pointy
@Pointy: True... I meant "apart from that..." :)
Daniel Vassallo
A: 

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');
});
Cirrostratus
No, that sets the background colour to 'red' onmouseover and onmouseout.
David Dorward
Corrected the code by adding a handlerOut object
Cirrostratus
+2  A: 

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
A: 

// 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
I don't use JQuery but binding is the answer, thank you :)
2x2p1p