How to detect a touchscreen without having problems with full page cache

Usually, you need to detect a touchscreen if you want to check the presence of the scrollbar.

The simplest and most effective way to detect the touchscreen without having issues with the full page cache is adding a CSS class to the HTML element via JavaScript.

Better to have the class available before the browser starts the rendering to avoid ugly layout shifts during the page loading.

So, just add this code in your functions.php or your functional plugin:

 

add_action( 'wp_head', 'eos_detect_touchscreen' );
/**
* Add a class to the HTML element depending on the presence of a touchscreen
*/
function eos_detect_touchscreen(){
?>
<script>
    try {
        document.createEvent("TouchEvent");
        document.documentElement.className += ' eos-touchscreen';
    } catch (e) {
        document.documentElement.className += ' eos-no-touchscreen';
    }
    </script>
<?php
}

 

If the page is visited by a touchscreen device the HTML will have the class “eos-touchscreen”, in another case it will have the class “eos-no-touchscreen”.

 

That’s it.