0

I have class .one, and when you view on mobile, on smaller viewport than 700px, I want change that class to .two ?

How is that possible, thanks?

Aleksandar Misin
  • 135
  • 2
  • 10

5 Answers5

4

You can use the "resize" event :

$( window ).resize(function() {
    if ($(window).width() < 700 ) {
       $('.one').addClass('two').removeClass('one');
    } else {
        $('.two').addClass('one').removeClass('two');
    }
});
Adrien LUCAS
  • 157
  • 1
  • 4
2

I think you're trying to solve the wrong problem. Just because your viewport changes, does that mean the item the class is applied to is changing?

Instead, a neater way is use the same class (which, after all, is a way of describing the content) and a @media query to set the styling:

.myClass {
    font-weight: bold;
    font-size: 1.2em;
}

@media (max-width: 750px) {
    .myClass {
       font-size: 1.0em;
    }
}

See MDN for more details.

Adrian Wragg
  • 7,311
  • 3
  • 26
  • 50
2

Simple:

if ($(window).width() < 700) {
   $( "parentelement" ).removeClass( "one" ).addClass( "two" );
}

I'm sure you can even make it:

 if ($(window).width() < 700) {
       $( "body" ).removeClass( "one" ).addClass( "two" );
    }

To make all "one" classes replaces with class "two"

To make sure it works when a user resizes the browser window I would also enclose it in a window resize i.e:

 $(window).resize(function() {
       if ($(window).width() < 700) {
               $( "body" ).removeClass( "one" ).addClass( "two" );
            }
    });

Or to just have it on startup you can enclose it in a document ready:

$(document).ready(function() {
 if ($(window).width() < 700) {
               $( "body" ).removeClass( "one" ).addClass( "two" );
            }

});
Terryfrancis
  • 135
  • 1
  • 12
1

You can use:

$( window ).resize(function() {
 if ($(window).width() <= 700)
  $('.one').addClass('two').removeClass('one')
 else
  $('.two').addClass('one').removeClass('two')
}).trigger('resize');
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125
0

Get the size of the browser, and change the class accordingly. Keep a variable with the current state, so that you only change the class when the state changes.

For example, changing the class on the body element:

$(function(){

  setSize();
  $(window).resize(setSize);

  var isMobile = false;

  function setSize() {
    var w = $(window).width();
    if (w < 700 && !isMobile) {
      isMobile = true;
      $('body').removeClass('one').addClass('two');
    } else if (w >= 700 && isMobile) {
      isMobile = false;
      $('body').removeClass('two').addClass('one');
    }
  }

});
Guffa
  • 687,336
  • 108
  • 737
  • 1,005