Caio
Caio

Reputation: 3215

Temporary Onmouseover

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

Upvotes: 3

Views: 1876

Answers (4)

james_womack
james_womack

Reputation: 10306

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');
});

Upvotes: 0

BrunoLM
BrunoLM

Reputation: 100361

// jQuery 'Temporary mouseevents'

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

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

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

Upvotes: 0

Guffa
Guffa

Reputation: 700512

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.

Upvotes: 2

Daniel Vassallo
Daniel Vassallo

Reputation: 344401

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.

Upvotes: 1

Related Questions