Category Archives: Modernizr

Modernizr: Detecting Touch Devices vs Non Touch Devices

Modernizr has a great feature that allows us to detect whether the browser is running on a touch device (iPad, smartphones, etc) or on a non-touch device (laptop, computer, etc).

Even though most modern touch devices support “proximity” hovering (navigating without touching the device screen), the browsing experience still suffer when dealing with onmouseover and onmouseout events.

So, let’s assume we want to implement WordPress’ Posts table. When we hover over any table row on a non-touch device, it will show additional actions such as “Edit”, “Quick Edit”, “Trash” and “View”. When we view the same page on a touch device, it will show the action without the hovering option.

The table may look something like this:-

<table class="table-actionable">
    <tr>
        <th>Artist</th>
        <th>Song Title</th>
    </tr>
    <tr>
        <td>System Of a Down</td>
        <td>Toxicity
            <ul class="hidden-action hide">
                <li><a href="/epic-app/buy/1">Buy</a></li>
                <li><a href="/epic-app/sell/1">Sell</a></li>
                <li><a href="/epic-app/trash/1">Trash</a></li>
            </ul>
        </td>
    </tr>
    <tr>
        <td>Eminem</td>
        <td>Rap God
            <ul class="hidden-action hide">
                <li><a href="/epic-app/buy/2">Buy</a></li>
                <li><a href="/epic-app/sell/2">Sell</a></li>
                <li><a href="/epic-app/trash/2">Trash</a></li>
            </ul>
        </td>
    </tr>
</table>

With Modernizr, we can now write something like this:-

<script>
    // On non-touch devices, show action list on mouse over and hide it on mouse out.
    if ( !Modernizr.touch ) {
        $( '.table-actionable tr' )
                .mouseover( function () {
                                $( this ).find( '.hidden-action' ).removeClass( 'hide' );
                            } )
                .mouseout( function () {
                               $( this ).find( '.hidden-action' ).addClass( 'hide' );
                           } );
    }
    // On touch devices, always show action list.
    else {
        $( '.hidden-action' ).removeClass( 'hide' );
    }
</script>

Shitty epic…

Advertisements