Is there any way that I can call a JavaScript function via css?
For example, from this :hover style:
.first-nav li a:hover,
.first-nav li.hover a {
margin:-3px 0 -1px;
height:30px;
position:relative;
background:url(../images/nav-hover.jpg) no-repeat;
}
The JavaScript function I want to call is on an anchor :hover.
No, you can’t trigger JavaScript from CSS directly.
What you can do is use CSS selectors to find the elements you want to watch in this way, and then watch for mouse events. The standard events are
mouseoverandmouseout, but they can be a bit tricky to work with because they bubble (you getmouseout, for instance, whenever the mouse leaves any descendant element). With appropriate logic, though, they’re not to bad to work with, and in fact if you have lots of these, you probably want to usemouseoverandmouseoutrather than the alternative below because you can set them on just a parent container and then work out which descendant element is involved, which can be simpler in some cases (and more complicated in others).IE provides
mouseenterandmouseleavewhich are much easier to work with because they don’t bubble, but (of course) IE-specific. These are so handy that frameworks are starting to support them even in browsers that don’t; Prototype and jQuery provide them, for instance, and I wouldn’t be too surprised if some other frameworks do as well. jQuery also provides the handyhoverfunction, which would be very close to what you want:…which is really just a shortcut for setting up
mouseenterandmouseleavehandlers, but still, wonderfully concise.In Prototype it’s quite similar:
(OT: In both cases, I’ve used anonymous inline function expressions just to avoid giving the impression you have to use named functions. I always recommend using named functions in production code, though.)