"Is Touch Device" condition (for interactions and animations)
Oliver Osswald
Just an idea: add a code snippet to a WordPress site to determine if the visitor is using a touch device, and then store the result in a global variable. For instance:
Code Snippet to Detect Touch Device
JavaScript Detection:
We'll use JavaScript to detect if the device is a touch device.
Setting a Global Variable:
This variable can be accessed by other scripts on your WordPress site.
JavaScript Code Snippet:
// Detect Touch Device
function isTouchDevice() {
return (('ontouchstart' in window) ||
(navigator.maxTouchPoints > 0) ||
(navigator.msMaxTouchPoints > 0));
}
// Set Global Variable
window.isTouch = isTouchDevice();
Integration with WordPress:
Add the Script:
You can add this script to your WordPress theme's functions.php file using the wp_enqueue_script function.
Ensure it Loads in the Footer:
So it doesn't block the loading of your page's content.
Example Usage in WordPress:
Once you have the global variable isTouch, you can use it in your other scripts like this:
if (window.isTouch) {
// Code for touch devices
} else {
// Code for non-touch devices
}
Steps to Add the Script to WordPress:
Create a New JS File:
Put the JavaScript code in a new file, e.g., touch-detection.js.
Upload the File:
Place this file in your theme's directory.
Edit functions.php:
Add the following code to your theme's functions.php:
function enqueue_touch_detection_script() {
wp_enqueue_script('touch-detection', get_template_directory_uri() . '/touch-detection.js', array(), false, true);
}
add_action('wp_enqueue_scripts', 'enqueue_touch_detection_script');
Testing:
Ensure you test this on various devices to confirm its effectiveness.
Caching:
Be aware that caching plugins or server-side caching might affect how scripts are loaded and executed.
Compatibility:
This method is generally compatible with most modern browsers.
robotdance
Oliver Osswald: yeah, I know. But it would be nice, if this is included inside breakdance (don‘t know how the UI would look like).