admin管理员组文章数量:1426489
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();
});
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();
});
Share
Improve this question
edited Jul 6, 2015 at 14:56
stevenw00
1,1561 gold badge13 silver badges22 bronze badges
asked Jul 6, 2015 at 14:32
CaspertCaspert
4,38316 gold badges68 silver badges111 bronze badges
1
-
While I don't know what happens when
isMobile
is toggled, you can probably achieve what you're ultimately trying to do with a simple media query without having to use JavaScript and/or jQuery. – TylerH Commented Jul 6, 2015 at 14:53
3 Answers
Reset to default 5Because 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();
});
Move var w = $(window).width();
inside resizer()
. This will get the value of current dimensions of window
.
See the ments 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
you can use these ways:
- Method 1: Check if the user is on a mobile device
const isMobile = /Android/i.test(navigator.userAgent);
- Method 2: Check if the screen width is less than 680 pixels
const isMobileWidth = window.innerWidth < 680;
本文标签: jqueryHow to check if viewport is smaller than a certain width using javascriptStack Overflow
版权声明:本文标题:jquery - How to check if viewport is smaller than a certain width using javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745415444a2657662.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论