http://stilbuero.de Klaus Hartl – Stilbüro - Klaus Hartl


Jump to: Search, Additional Information.


Archive for July 19th, 2005

whatever:hover, fast and easy

A way to easily implement whatever:hover in your IE/Win specific style sheet (you know, you should use Conditional Comments) is using Dynamic Properties.

Have a look at the following snippet:

.whatever {
    background-color: expression('#808080',
        this.onmouseover = function() { this.runtimeStyle.backgroundColor = '#eaeaea'; },
        this.onmouseout = function() { this.runtimeStyle.backgroundColor = '#808080'; });
}

It looks a bit odd, but it works! Here is a little demo page.

I like this solution a lot, because using htc-files always ended up in a hassle for me. And I like beating IE with his own weapons.

Update: It is of course better to avoid having to define the same styles in two different style sheets. One should use a class and just change the class attribute on mousover/mouseout. Here is an complete example (taken from the demo page) – first the CSS for all browsers:

.whatever {
    background: #808080;
}
.whatever:hover, .whateverhover {
    background: #eaeaea;
}

IE's extra CSS:

.whatever {
    background-color: expression(this.runtimeStyle.backgroundColor,
        this.onmouseover = function() { this.className += ' whateverhover'; },
        this.onmouseout = function() { this.className = this.className.replace('whateverhover', ''); });
}

Update: I got a tip at the css-discuss mailing list, that one can even leave out the first part of the expression – this.runtimeStyle.backgroundColor:

.whatever {
    background-color: expression(
        this.onmouseover = function() { this.className += ' whateverhover'; },
        this.onmouseout = function() { this.className = this.className.replace('whateverhover', ''); });
}

Thanks Brett!

Update: I got another hint from the css-d mailing list: The described technique fails in IE 5/Win, probably because of the braces { } inside the declaration.

Fortunately there is another way to create an anonymous function in JavaScript:

var myFunction = new Function([param1[, param2[,...paramN]]], "statement1[; ...statementN;"]);

That way, whatever:hover – fast and easy – works in that old browser as well:

.whatever {
    background-color: expression(
        this.onmouseover = new Function("this.className += ' whateverhover';"),
        this.onmouseout = new Function("this.className = this.className.replace('whateverhover', '');")
    );
}

One last thing to mention: The technique does not work in IE/Mac. That browser simply does not support Dynamic Properties.



Klaus Hartl – Stilbüro is powered by WordPress, jQuery, XHTML, CSS and me.