Change class with javascript when resizing screen

7

I need a javascript code that changes the menu class to the responsivemenu class when the screen resolution is less than 750px .

    
asked by anonymous 30.11.2015 / 17:54

3 answers

15

Using JavaScript

Note that I'm checking the size within block window.addEventListener('resize', function() {..}); , the function will be called every time the screen resolution changes.

window.addEventListener('resize', function () {
    //var altura = window.innerHeight;
    var largura = window.innerWidth;

    if (largura < 750) 
        document.getElementsByClassName('menu')[0].className = 'responsivemenu';
});

Using CSS Media Query

The simplest way to use Media Query is to define specific style sheets for each type of device, so you just need to add the media property to define what kind of device your css will be used. Use handheld for handheld devices, cell phones, and other devices in this profile. Usually with small screens and limited bandwidth.

<link rel="stylesheet" href="estilo.css" type="text/css" media="handheld">

Now the form that I believe to be more correct, in your style file you will use conditionals to set the style for each resolution you want.

/* Estilo padrão */
menu {
  color: blue;
}

/* Estilo para resolução menor que 750 pixels */
@media screen and (max-width: 750) {
  menu {
    color: green;
  }
}

Within the block you will set the specific style for the resolution.

Source : Introduction to Media Queries

    
30.11.2015 / 18:27
3

There are several ways to do this.

With Jquery, for example, it can be done like this:

if ($(window).width() <= 750)
  $('.menu').removeClass('menu').addClass('responsivemenu');
  // ou
  $('.menu').attr('class','responsivemenu');

There are several ways to do this.

If you'd like to delve deeper into this method I've presented, take a look at link

    
30.11.2015 / 18:21
2

Friend, try the following form.

if(window.screen.availWidth<750){
  $('.menu').addClass('responsivemenu').removeClass('menu');
}
    
30.11.2015 / 18:10