Skip to content

Instantly share code, notes, and snippets.

@mathetos
Created June 19, 2014 21:35
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mathetos/4d80d5c7bf2d23fd2a7e to your computer and use it in GitHub Desktop.
Save mathetos/4d80d5c7bf2d23fd2a7e to your computer and use it in GitHub Desktop.
Targeting Mobile Devices
<!DOCTYPE html>
<html>
<head>
<title></title>
<script src="//code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"></script>
<script type="text/javascript">
// Small script to detect mobile browsers and toggle the visibility of specified elements.
(function($){
var isMobile = function(_, ua){
_.Android = ua.match(/Android/i);
_.BlackBerry = ua.match(/BlackBerry/i);
_.iOS = ua.match(/iPhone|iPad|iPod/i);
_.Opera = ua.match(/Opera Mini/i);
_.Windows = ua.match(/IEMobile/i);
_.Palm = ua.match(/webOS/i);
_.any = _.Android || _.BlackBerry || _.iOS || _.Opera || _.Windows || _.Palm;
_.selector = {
hide: '.on-desktop', // the selector to hide when on a mobile
show: '.on-mobile' // the selector to show when on a mobile
};
_.show = function(){
$(_.selector.hide).hide();
$(_.selector.show).show();
};
_.hide = function(){
$(_.selector.show).hide();
$(_.selector.hide).show();
};
_.toggle = function(clause){
clause = typeof clause !== 'boolean' ? _.any : clause;
if (clause) _.show();
else _.hide();
};
return _;
}({}, navigator.userAgent);
$(function(){
// check for any
isMobile.toggle();
// isMobile.toggle(isMobile.any);
//
// Check for single
// isMobile.toggle(isMobile.Android);
//
// Check for multiple
// isMobile.toggle(isMobile.Android || isMobile.BlackBerry);
});
})(jQuery);
</script>
</head>
<body>
<div class="on-desktop">
I'm visible on a desktop browser.
</div>
<div class="on-mobile">
I'm visible on a mobile browser.
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment