#1 A simple method to test if is touch device in JavaScript
1 2 3 4 5 6 7 8 |
function is_touch_device() { try { document.createEvent("TouchEvent"); return true; } catch (e) { return false; } } |
And if you combine that with a simple screen width conditional it can become something useful.
1 2 3 4 5 6 7 |
(function($) { jQuery( document ).ready(function($) { if ( $(window).width() > 768 && is_touch_device() ) { //JQUERY, DO SOMETHING COOL! } }); })(jQuery); |
Has anyone a better idea? Post it in the comments. I would love to hear it.
#2 Have you wondered what WordPress script localization does?
The cleanest method to pass variables from Php to JavaScript in WordPress is by using localization function.
Something like this used in your functions.php file:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
<?php /** * Pass php to javascript. */ function custom_scripts() { $firstname = "John"; $lastname = "Doe"; $website = "johndoe.com"; wp_register_script( 'custom-actions', get_stylesheet_directory_uri() . '/js/actions.js', array(), '20160920', true ); $translation_array = array( 'firstname' => $firstname, 'lastname' => $lastname, 'website' => $website, 'ajaxurl' => admin_url('admin-ajax.php') ); wp_localize_script( 'custom-actions', 'settings', $translation_array ); wp_enqueue_script( 'custom-actions' ); } add_action( 'wp_enqueue_scripts', 'custom_scripts' ); |
In JavaScript you would call them like this:
1 2 3 4 5 |
// VARIABLES FROM PHP var firstname = settings.firstname; var lastnmae = settings.lastname; var website = settings.website; var ajaxurl = settings.ajaxurl; |
The above technique simply works and it’s really useful but have you ever wondered what happens under the hood?
Behold!
1 2 3 4 5 |
<script type='text/javascript'> /* <![CDATA[ */ var settings = {"firstname":"John","lastname":"Doe","website":"johndoe.com","ajaxurl":"http:\/\/www.johndoe.com\/wp-admin\/admin-ajax.php"}; /* ]]> */ </script> |