V
V
v-orlov2015-10-15 17:25:12
JavaScript
v-orlov, 2015-10-15 17:25:12

How to make $(window).width() dynamically fired?

For example, there is a code:

if ($(window).width() < 480) {
    $('.wow').addClass('slider');
}
else {
    $('.wow').removeClass('slider');
}

that is, if the screen width is 480, then add a class, if less, remove it. but this script only fires when the page is refreshed. reduced the screen -> updated -> saw the class.
yes, theoretically, sites are not conceived as an accordion, on which the user will sit to play with the width of the browser. I went in - the width was determined - I saw the display that the developers had in mind.
but still, how to "dynamically" determine the width and remove/add a class? without reloading
i was thinking on some $(window).resize(); but I can’t think of a logic
if someone came across something similar, thank you in advance for your help and advice)

Answer the question

In order to leave comments, you need to log in

4 answer(s)
V
Vitaly Inchin ☢, 2015-10-15
@In4in

$(function(){
  $(window).resize(function(){
    $('.wow').toggleClass('slider', $(window).width() < 480);
  }).resize()
});

A
Anton Shamanov, 2015-10-15
@SilenceOfWinter

make a function out of this code and bind it to resize and load

D
Dasha Tsiklauri, 2015-10-15
@dasha_programmist

I'll add to the answer above: move $('.wow') outside the resize callback:

var wow = $('.wow');
$(window).resize(function(){
  if(...)
    wow.addClass('slider');
else
    wow.removeClass('slider');
});

UPD:
var barrierWidth = 480;
var belowBar = currentWidth<480;
var wow = $('.wow');
function recalc(width){
  if(width<barrierWidth && !belowBar)
    wow.addClass('slider');
  else if(width>barrierWidth && belowBar)
    wow.removeClass('slider');
};
$(window).resize(function(){
    recalc(width);
});

V
v-orlov, 2015-10-15
@v-orlov

The suggested options worked, thanks. but the slider puzzled me)
it leaves 20 more classes inside my .wow list, that is, cleaning everything is long and wrong.
how to auto reload on some specific browser width? that is, they started to shrink the window, reached 480, caught a reboot, and so on? so that there is a constant reload on 480
(I just try for myself, on a real project, of course, doing this is nonsense)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question