Reputation: 4363
I want to have a simple statement to set a variable bool to false or true. isMobile should be set to true when the viewport is smaller then 768px and above this amount it should be set to false.
I don't know why the following code does nothing. Also there is no error in the console log.
var w = $(window).width();
var isMobile = false;
function resizer() {
if (w < 768) {
console.log("resize");
isMobile = true;
} else {
isMobile = false;
}
}
$(window).resize(function() {
resizer();
});
Upvotes: 2
Views: 2449
Reputation: 21
you can use these ways:
const isMobile = /Android/i.test(navigator.userAgent);
const isMobileWidth = window.innerWidth < 680;
Upvotes: 0
Reputation: 2272
Because you don't measure the width on every resize. Try this way:
var isMobile = false;
function resizer() {
var w = $(window).width();
if (w < 768) {
console.log("resize");
isMobile = true;
} else {
isMobile = false;
}
}
$(window).on('load resize', function(){
resizer();
});
Upvotes: 5
Reputation: 87203
Move var w = $(window).width();
inside resizer()
. This will get the value of current dimensions of window
.
See the comments inline in the code.
var isMobile = false;
function resizer() {
var w = $(window).width();
// Move this inside resize handler
if (w < 768) {
console.log("resize");
isMobile = true;
} else {
isMobile = false;
}
}
$(window).resize(function() {
resizer();
}).trigger('resize');
// ^^^^^^^^^^^^^^^^^^
//
// Trigger event on page load
Upvotes: 2