Ender91
Ender91

Reputation: 71

jQuery function only works if I manually resize my window to mobile but not on refresh

I have a code snippet where I'm trying to add and remove classes on mobile only and it only works when I manually resize the browser to a mobile window, while when I refresh it, it doesn't work.

$(document).ready(function(){
 $(window).on('load, resize', function mobileViewUpdate() {
    var viewportWidth = $(window).width();
    if (viewportWidth <= 800) {
        $('.header').removeClass('header-transparent');
        $('#navdiv').removeClass('bottom_border');
        $('.navbar-main').addClass('nav-shadow');
        $('#nav-icon').addClass('navbar-toggler-icon2');
    }
  });
});

Upvotes: 0

Views: 213

Answers (2)

jeprubio
jeprubio

Reputation: 18002

Try extracting the mobileViewUpdate function:

function mobileViewUpdate() {
    var viewportWidth = $(window).width();
    if (viewportWidth <= 800) {
        $('.header').removeClass('header-transparent');
         $('#navdiv').removeClass('bottom_border');
        $('.navbar-main').addClass('nav-shadow');
     $('#nav-icon').addClass('navbar-toggler-icon2');
    }
}

And then call it from document.ready and on resize, both:

$(document).ready(function(){
 $(window).on('resize', mobileViewUpdate);
 mobileViewUpdate();
});

This should work. However, I think it would be better to set the meta viewport tag and use media queries instead to adapt the website for mobile.

Upvotes: 1

Taplar
Taplar

Reputation: 24965

While I agree with the other answer showing to extract the logic to a method and use it in both place (so as to not proxy logic through the DOM), it is still an option for you to trigger() the event on ready as well.

$(document).ready(function(){
  $(window).on('load, resize', function mobileViewUpdate() {
    var viewportWidth = $(window).width();
    if (viewportWidth <= 800) {
        $('.header').removeClass('header-transparent');
         $('#navdiv').removeClass('bottom_border');
        $('.navbar-main').addClass('nav-shadow');
     $('#nav-icon').addClass('navbar-toggler-icon2');
    }
  }).trigger('resize');
});

Upvotes: 1

Related Questions