0

I just wanted to check, I am trying to add a window width condition in my function, Is this the best way to do it? So this is similar to a media query, in the sense of Min width and Max width

if ($(window).width() <= 440 && $(window).width() <=768) {
// Do something
}
Sole
  • 3,100
  • 14
  • 58
  • 112
  • window.innerWidth and window.innerHeight are what you are probably looking for. These questions have more info: [Get the size of the screen, current web page and browser window](https://stackoverflow.com/questions/3437786/get-the-size-of-the-screen-current-web-page-and-browser-window) and [What is the difference between window.innerWidth and screen.width?](https://stackoverflow.com/questions/37443482/what-is-the-difference-between-window-innerwidth-and-screen-width) – nageeb Nov 12 '19 at 17:09
  • What is the best way? It depends on the task. What is the problem you face? I can tell you doing `$(window).width()` multiple times is not the best way. – epascarello Nov 12 '19 at 17:09
  • Question updated – Sole Nov 12 '19 at 17:13
  • I assume you run the code on resize? – epascarello Nov 12 '19 at 17:14
  • https://stackoverflow.com/questions/31511001/is-there-a-javascript-equivalent-to-using-media-query – epascarello Nov 12 '19 at 17:15

1 Answers1

1

1. Less than 440 AND less than 768 doesn't make sense. You probably wanted greater than 440 less than 768.

2. You should wrap it around window resize to trigger the action on window resize.

$(window).on('resize', function(){
if ($(window).width() >= 440 && $(window).width() <=600) {
$(".content").html("Between 440 and 600");
}
else if($(window).width()> 600) {
$(".content").html("Bigger than 600");
}
else if($(window).width()< 440) {
$(".content").html("Smaller than 440");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="content">Resize the window</div>
Evik Ghazarian
  • 1,803
  • 1
  • 9
  • 24