I am looking to determine whether the device is a desktop, mobile, or tablet. Based on this information, I want to switch the image directory accordingly.
if (getDeviceState() == 'phone') {
alert("phone");
}
else if (getDeviceState() == 'tablet') {
alert("tablet");
}
else {
alert("small-desktop");
}
I have attempted to achieve this using both CSS and JavaScript.
var indicator = document.createElement('div');
indicator.className = 'state-indicator';
document.body.appendChild(indicator);
// Create a method to determine device state
function getDeviceState() {
var index = parseInt(window.getComputedStyle(indicator).getPropertyValue('z-index'), 10);
var states = {
2: 'small-desktop',
3: 'tablet',
4: 'phone'
};
return states[index] || 'desktop';
}
if (getDeviceState() == 'phone') {
alert("phone");
}
else if (getDeviceState() == 'tablet') {
alert("tablet");
}
else {
alert("small-desktop");
}
And in the CSS:
/* small desktop */
@media all and (max-width: 1200px) {
.state-indicator {
z-index: 2;
}
}
/* tablet */
@media all and (max-width: 768px) {
.state-indicator {
z-index: 3;
}
}
/* mobile phone */
@media all and (max-width: 360px) {
.state-indicator {
z-index: 4;
}
}
However, I am encountering difficulties distinguishing between landscape and portrait states. Thus, it may be more effective to use user agents rather than relying solely on CSS.