简体   繁体   中英

Resizing browser with min width conditional

    var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

    $(window).on("resize", function(){
        if(width < 767 ){
            console.log('narrow');
            $('.col-xs-6.col-sm-3.thumbnail.promo:eq(2)').css('margin-left', '0px');
        };
    });

The following code console.logs the message only when the browser is less than 767px and not when its above 767px as expected. But It seems to ignore the 'width < 767' when you resize the browser. If you start on less than 767 it logs the message anytime you resize. where as when its larger than 767px, it never logs the message. Is there a way for the resize to trigger the the code that runs inside the width < 767?

You're only calculating the width once... you need to recalculate it every time the window is resized:

$(window).on("resize", function(){
    if($(window).width() < 767 ){
        console.log('narrow');
        $('.col-xs-6.col-sm-3.thumbnail.promo:eq(2)').css('margin-left', '0px');
    };
});

you need to move the calculation inside the resize handler

$(window).on("resize", function(){
    var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
    if(width < 767 ){
        console.log('narrow');
        $('.col-xs-6.col-sm-3.thumbnail.promo:eq(2)').css('margin-left', '0px');
    };
});

You shouldn't be using JavaScript for this. You can do this with CSS only:

@media (max-width: 766px) {
  .col-xs-6.col-sm-3.thumbnail.promo:eq(2) {
    margin-left: 0;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM