Make JavaScript work on a certain screen size

1

Hello! I'm setting up a responsive site and using some bootstrap layouts to make the site. The problem is that the layout I liked the most was not done with a good menu for a lot of content, especially for users with a screen less than 768px.

So I had an idea, use JS so that above 768px I have one kind of layout and another below. Yes I use media querie , but as they are bootstrap layouts I need to take and put some classes in html depending on the size of the screen and just do it by JS (as far as I know).

So, I have the script that I did when I resize the screen to enter the style I want, but the problem is that if the person enters through a cell phone, they will not resize the screen and will not enter the layout automatically.

var $element = $("nav");
    $(window).resize(function () {    
        /*Abaixo de 768px, add a classe .navbar-inverse*/
        if (window.innerWidth < 768) {
            $element.addClass("navbar-inverse");
        /* Acima de 768px, se existir a classe navbar-inverse ela é retirada*/
        } else {
            $element.removeClass("navbar-inverse");
        }
    });

In short, I need when the person enters a resolution below 768px he adds the .navbar-inverse class and when he resizes it in the browser and enters that script that is ready .

Thank you for your attention!

    
asked by anonymous 14.04.2015 / 16:51

2 answers

4

You can force the event to be called through the trigger method, doing so shortly after setting it can solve your problem

$(window).resize(function(){
    //seu código aqui
}).trigger("resize");
    
14.04.2015 / 17:03
0

If all you want is for a given style to be applied only when the screen is less than 768px, then the best option would be to use only CSS.

@media screen and (max-width: 768px) {
    .navbar-inverse {
        /* estilos */
    }
}
    
14.04.2015 / 17:33