When I write similar code:

if (window.matchMedia('(min-width: 761px)').matches) { } 

Some changes in brackets only occur when the page loads, and already when the size of the loaded page changes, nothing changes. I decided to take the window size using the resize function like this:

 $(window).resize(function () { var widthWind = $(this).width(); if (widthWind <= 750) {}}); 

Tell me, am I on the right track or is there a better alternative? After all, the resize function is called many, many times.

  • one
    If the code in the resize event handler is optimized (there are no heaps of meaningless and merciless "hard" operations with each call of the handler), then this is quite a normal approach. - Regent
  • Is there an alternative? - Alexander Alekseev
  • You can, for example, just once in X milliseconds ( setInterval ) check the width and perform the appropriate actions. - Regent
  • 2
    Personally, I would use media queries. This is a standard approach, it is more logical, more convenient for subsequent editing, does not require extra calculations, especially every second (for mobile devices it is quite critical), if the script does not load, the layout does not go, and, finally, the layout should be layout and scripts - scripts. - qtm
  • @qtm and what to do if media requests for js work only at the moment of loading the page, but do not work when the window is changed (read the beginning of my topic). Or am I doing something wrong? - Alexander Alekseev

1 answer 1

Found the answer about media queries and why they didn’t work dynamically.
The answer is here .

 var handleMatchMedia = function(mediaQuery) { if (mediaQuery.matches) { // если менее 480px или равное, то выполняется код между скобок } else { // обратное условие, т.е если более 480px } }, mql = window.matchMedia('all and (max-width: 480px)'); handleMatchMedia(mql); mql.addListener(handleMatchMedia); //запускается каждый раз, когда заданное разрешение медиа запроса достигнуто