The following is how to run javascript that should only be run on tablets. The idea is that you have a div with a width and height of 0. When you are on a tablet, the media query will set the width to 1px. jQuery will then detect the width of the div and do its thing.
To your html add
<div id="device-detect"></div>
Add to your CSS
#device-detect{ height:0; width:0; } @media only screen and (min-device-width: 768px) and (max-device-width: 1280px){ #device-detect{ width:1px; } }
To your scripts add inside $(document).ready(function() {
if($('#device-detect').css('width') == '1px'){ //tablet-only functions here };
If anyone knows an alternative or better way, let me know.
—
I used this on Palmer Printing to deliver different js to tablets. Below is the full javascript including how I targeted only phones.
if (document.documentElement.clientWidth > 767) { //scripts for tablets and desktops $(document).ready(function() { $('#nav-main .nav').superfish({ animation: { opacity: 'show', height: 'show' }, autoArrows: false }); $('#nav-sup .nav').superfish({ animation: { opacity: 'show' }, autoArrows: false }); //detect if this is a tablet. In the css is a media query that only tablets will recognize, it will set the width of a div to 1px if($('#device-detect').css('width') == '1px'){ //creates duplicate top level link and adds it to the dropdown $('#nav-main ul.nav > li > a').each(function(){ var newLink = '<li>' + $(this).clone().wrap("<div />").parent().html() + '</li>'; $(this).next('ul').prepend(newLink); $(this).attr('href', 'javascript: void(0)'); }); }; }); } else { //scripts for phones (width under 768px) $(document).ready(function() { //disable flash intro on phones (yes I know android can do it, but it breaks the homepage) $('.home #flash').css('display','none'); //show html homepage $('.home #non-flash').css({'height':'auto','overflow':'auto'}); //close all dropdowns $('ul.nav ul').css('display','none').parent('li').addClass('closed'); //creates duplicate top level link and adds it to the dropdown $('#nav-main ul.nav > li > a').each(function(){ var newLink = '<li>' + $(this).clone().wrap("<div />").parent().html() + '</li>'; $(this).next('ul').prepend(newLink); $(this).attr('href', 'javascript: void(0)'); }); //controls the toggling of the dropdowns $('ul.nav > li.closed > a').live('click', function(){ $('ul.nav ul').slideUp('slow').parent('li').removeClass('open').addClass('closed'); $(this).next('ul').slideDown(300).parent('li').removeClass('closed').addClass('open'); return false; }); $('ul.nav > li.open > a').live('click', function(){ $(this).next('ul').slideUp(300).parent('li').removeClass('open').addClass('closed'); return false; }); }); };
Just thinking out loud here…
Why not check the orientation and touch properties of the browser? I can’t think of a reason that a non-mobile would have both.
I needed a way to only run certain JS when on a tablet. Phones and desktops should not run that JS. Your code targets both tablet and phones.