Skip to content

Instantly share code, notes, and snippets.

@vandorjw
Created March 14, 2015 20:10
Show Gist options
  • Save vandorjw/2300d82f75f68555f82b to your computer and use it in GitHub Desktop.
Save vandorjw/2300d82f75f68555f82b to your computer and use it in GitHub Desktop.
<html>
<head>
<meta charset="UTF-8">
<title>Refactored TapeDeck</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap-theme.min.css">
<script src="https://code.jquery.com/jquery-2.1.3.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/js/bootstrap.min.js"></script>
<style>
#mobileView { width: 1px; display:none; }
#tabletView { width: 0px; display:none;}
#desktopView { width: 0px; display:none;}
@media (min-width:600px) and (max-width:992px) {
#mobileView { width: 0px;}
#tabletView { width: 1px; }
#desktopView { width: 0px;}
}
@media (min-width:992px) {
#mobileView { width: 0px; }
#tabletView { width: 0px; }
#desktopView { width: 1px; }
}
</style>
<script>
var device_type; // Keep me global, or encapsulate me in a namespace.
window.onresize = function () {
setDeviceType();
if(device_type === "mobile" ){
console.log("We are in mobile view!");
}
else if (device_type === "tablet"){
console.log("We are in tablet view!");
}
else{
console.log("We are in desktop view!");
}
};
window.onload = function () {
setDeviceType();
if(device_type === "mobile" ){
console.log("We are in mobile view!");
}
else if (device_type === "tablet"){
console.log("We are in tablet view!");
}
else{
console.log("We are in desktop view!");
}
};
function setDeviceType(){
if ($('#mobileView').width() > 0 ){
device_type = "mobile";
}
else if ($('#tabletView').width() > 0 ){
device_type = "tablet";
}
else if ($('#desktopView').width() > 0 ){
device_type = "desktop";
}
}
</script>
</head>
<body>
<div id="mobileView">mobile</div>
<div id="tabletView">tablet</div>
<div id="desktopView">desktop</div>
<h1>Device Detection based on CSS breakpoints</h1>
<p>The purpose of this snippet is to show it is possible to know the device type in javascript,
based on CSS media querries.</p>
<h2> Use Case</h2>
<pre>
//
// myArray needs to be different length, depending on viewport width
//
if(device_type === "mobile" ){
myArray = Array(6);
}
else if (device_type === "tablet"){
myArray = Array(12);
}
else if (device_type === "desktop"){{
myArray = Array(24);
}
else{
console.log("ya'll got problems!");
}
</pre>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment