Search the blog

If you’ve ever tried to add a click event to html or body in jQuery, you’ll have no doubt found it doesn’t work on iOS. Click events do not bubble up to the html or body tags in iOS. This is problematic if, for example, you are developing a drop down menu and you want it to close when the document is clicked.

Actually, click events do bubble if the html or body tags have the CSS cursor property to pointer. Because iOS is for touch devices only, setting this property shouldn’t cause any cosmetic issues. However, when elements are clickable in iOS you get a flash of colour; this is the -webkit-tap-highlight-color property and provides useful feedback to the user that something was clicked. Unfortunately, this looks a little odd when added to the html or body tags as you get a flash of colour that is confusing.

You can remove this by setting -webkit-tap-highlight-color to rgba(0, 0, 0, 0) but it means you lose this visual feedback when legitimate links are clicked.

Bearing all of the above in mind, here's a complete code listing on how to add a click event to html or body on iOS using jQuery. It involves sniffing the user agent, which I don’t like doing — but it’s a necessary evil. We sniff by device rather than browser as this is an issue intrinsic with Webkit on iOS rather than a particular browser.

$(function() {

    // Check if it is iOS
    var isiOS = (navigator.userAgent.match(/(iPad|iPhone|iPod)/g) ? true : false);
    
    if(isiOS === true) {
    
        // Store -webkit-tap-highlight-color as this gets set to rgba(0, 0, 0, 0) in the next part of the code
        var tempCSS = $('a').css('-webkit-tap-highlight-color');
        
        $('body').css('cursor', 'pointer')                                    // Make iOS honour the click event on body
                 .css('-webkit-tap-highlight-color', 'rgba(0, 0, 0, 0)');     // Stops content flashing when body is clicked
             
        // Re-apply cached CSS
        $('a').css('-webkit-tap-highlight-color', tempCSS);
    
    }

});
Tim Bennett is a web designer and developer. He has a First Class Honours degree in Computing from Leeds Metropolitan University and currently runs his own one-man web design company, Texelate.