Handling css :hover on iPad

As you are all well aware, there’s a mobile revolution going on right now, and this revolution has several consequences for website implementation.

I encountered one of those today. I needed to implement a mega dropdown navigation that would allow the user to hover over each element in the top navigation in order to produce a dropdown navigation. Clicking the element in the top navigation would forward the user to the page being linked to.

I created the mega dropdown navigation in pure CSS only to realize that I needed special code in order to handle users with tablets and smartphones. You can use the CSS :hover pseudo-class on tablets and smartphones, but it doesn’t work on iOS-devices.

It turned out that the solution was quite simple. You just need to detect the users’ operating environment via JavaScript, and then override the click-event. Just like this:

(function($) {
    $(document).ready(function() {
        // Emulate hover on tablets and smartphones
        if ((navigator.userAgent.match(/iPhone/i)) || (navigator.userAgent.match(/iPod/i)) || (navigator.userAgent.match(/iPad/i))) {
            $("#menu li a").click(function() {
                return false;
            });
        }
    });
});

Thanks to Blake Petersen for the original source code.

About these ads

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s