JAVASCRIPT
Developers can utilize the userAgent located in the HTTP headers to see if the user is on a mobile device. A regular expression can be applied to the value of userAgent to see if it contains any keywords, and then the device type can be determined (mobile device, tablet, or desktop).
navigator.userAgernt Solution:
function deviceType() {
const a = navigator.userAgent;
if (/(tablet|ipad|playbook|silk)|(android(?!.*mobi))/i.test(a)) {
return "tablet";
}
else if (/Mobile|Android|iP(hone|od)|IEMobile|BlackBerry|Kindle|Silk-Accelerated|(hpw|web)OS|Opera M(obi|ini)/.test(ua)) {
return "mobile";
}
return "desktop";
};
console.log(deviceType());
Scroller Width Solution:
var a = document.getElementById('scroll1');
var b=document.getElementById('scroll2');
if (a.offsetWidth - dv.clientWidth < 10) {sp.innerHTML='Is mobile'; //return true;
} else {
b.innerHTML='It is not mobile'; //return false;
}
<div id="scroll1" style="position:fixed;top:0;left:0;width:50px;height:50px;overflow:hidden;overflow-y:scroll;z-index:-1;visibility:hidden;"></div>
<span id="scroll2"></span>
This function will examine the scroller’s width. Morever, it’s a mobile device if the scroller width is smaller than 10px. Therefore, “a.offsetWidth – dv.clientWidth < 10” will return a true statement if it meets the requirement. Of course, this is a fairly primitive approach. It’s simple to change the User-Agent attribute because it can be replicated. However, because it functions, you can use it to a variety of jobs. For example. Landing pages or custom redirects.
MEDIA QUERIES
CSS uses width (Media Queries) to determine which styles are applied to the web document based on width. The same method can be applied using JavaScript.
For instance, in Bootstrap’s (Mobile First) Media Queries, there exist 4 snap/breakpoints:
- Extra Small Devices are 768 pixels and under.
- Small Devices range from 768 to 991 pixels.
- Medium Devices range from 992 to 1199 pixels.
- Large Devices are 1200 pixels and up.
A function can be created that gets the window size and retu rns a value that allows us to see what size device is viewing our application:
Solution:
(function ($) {
// Write code here
var getBrowserWidth = function(){
if(window.innerWidth < 768){
// Extra Small Device
$('.box').css('background-colour','grey');
} else if(window.innerWidth < 991){
// Small Device
$('.box').css('background-colour','grey');
} else if(window.innerWidth < 1199){
// Medium Device
$('.box').css('background-colour','grey');
} else {
// Large Device
$('.box').css('background-colour','grey');
}
};
getBrowserWidth();
$(window).on('resize',function(){
getBrowserWidth();
});
}(jQuery));