Updated: Hover for non-anchor elements in IE6

The updated version of the previous version of Hover for non-anchor elements in IE 6.

Before proceeding further, here’s a brief description of the problem,

The ‘:hover’ pseudo-class works on all visual elements in IE 7+, FF, Safari, Chrome and Opera. But for obvious reasons IE 6 fails to recognize the ‘:hover’ pseudo-class for elements other than the anchor(<a></a>).

Here is the updated code, which is faster and is targeted only IE 6 by a combination of JavaScript conditional comments & feature detection.

    (function ($) {
        $(document).ready(function () {
            $.single=function(a){return function(b){a[0]=b;return a}}($([1]));
            /*@cc_on
                if (!window.XMLHttpRequest) {
                    $('.hoverable').each(function () {
                        this.attachEvent('onmouseenter', function (evt) { $.single(evt.srcElement).addClass('hovered'); });
                        this.attachEvent('onmouseleave', function (evt) { $.single(evt.srcElement).removeClass('hovered'); });
                    });
                }
            @*/
        });
    }(jQuery));

All you’ve to do is to include this script in your html document and add the class ‘hoverable’ to all the non-anchor elements to which you want the hover action. And in your stylesheet add an extra selector for the element along with the ‘:hover’ style definition. Look at the code of the updated example to get a clear idea.

I’ve used James Padolsey’s single jQuery object snippet in the event handlers to prevent the creation of a new jQuery object every time the event handler is executed, hence saving a few execution cycles and memory.

Related Posts

  1. Hover for non-anchor elements in IE6
This entry was posted in Javascript. Bookmark the permalink.

4 Responses to Updated: Hover for non-anchor elements in IE6

  1. Pingback: Hover for non-anchor elements in IE6 | Blog de Livi

  2. poupougnac says:

    Hi, I encourage you to test this jQuery plugin which definitively implement the :hover functionality on IE6. You don’t have to change anything on your code, just add and load the plugin.
    http://plugins.jquery.com/project/ie6hover

  3. livingston says:

    @poupougnac – I’d strongly recommend not to use that plugin, because it tries to parse the css files and apply fixes based on the selectors with hover defined. As IE 6 has very poor js performance and in any project with css files that have more than a few hundreds of lines this will result in a huge impact on the performance.

  4. Xiaopu says:

    This was very helpful! Thank you so much!

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>