Make Javascript work on a certain screen size

Asked

Viewed 553 times

1

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

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

Soon, below I have the script I made for when der resize on the screen enter the style I want, but the problem is that if the person enters by a mobile phone n will do the resize on 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 that when the person enters with a resolution below 768px he add the class .navbar-inverse and when it does resize in the browser and enter this script that is already ready.

Thank you for your attention!

2 answers

4


You can force the event to be called through the method trigger, doing this right after setting it may solve your problem

$(window).resize(function(){
    //seu código aqui
}).trigger("resize");

0

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

@media screen and (max-width: 768px) {
    .navbar-inverse {
        /* estilos */
    }
}
  • o . navbar-inverse is a bootstrap class already configured, if it is added to a tag it does not need any configuration.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.