Skip to content

Instantly share code, notes, and snippets.

@samarpanda
Last active May 23, 2019 09:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samarpanda/c99f033ace20721c961c9eb9026a6eac to your computer and use it in GitHub Desktop.
Save samarpanda/c99f033ace20721c961c9eb9026a6eac to your computer and use it in GitHub Desktop.
Device state detection with css media queries and javascript
var indicator = document.createElement('div');
indicator.className = 'state-indicator';
document.body.appendChild(indicator);
function getDeviceState(){
return parseInt(window.getComputedStyle(indicator).getPropertyValue('z-index'), 10);
}
if(getDeviceState() < 3){
//If desktop or small desktop
}
function getDeviceState(){
var index = parseInt(window.getComputedStyle(indicator).getPropertyValue('z-index'));
var states = {
2: 'small-desktop',
3: 'tablet',
4: 'phone'
};
return states[index] || 'desktop';
}
.state-indicator {
position: absolute;
top: -999em;
left: -999em;
z-index: 1;
}
@media all and (max-width: 1200px){
.state-indicator {
z-index: 2;
}
}
@media all and (max-width: 1024px){
.state-indicator{
z-index: 3;
}
}
@media all and (max-width: 768px){
.state-indicator{
z-index: 4;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment