1

How can I change an element's class when the viewport changes?

For instance, when Bootstrap renders an element on viewport lg, the elements have a class called css-class. But when the viewport is md, I need it to change that element class to css-class2

dazed-and-confused
  • 1,293
  • 2
  • 11
  • 19
Mike s
  • 119
  • 2
  • 13

1 Answers1

3

When you want to give classes to elements based on the viewport you could write a simple check in JavaScript based on Bootstrap's viewport.

if(screen.width >= bootstrap-viewport) {
  $(elements).removeClass('otherClasses');
  $(elements).addClass('someExampleClass');
}

You can however use media queries in CSS to give elements specific styling per viewport. This is a cleaner and more maintainable solution. A small example:

.content-area {
  line-height: 1.2em;
}

@media(min-width: @screen-desktop) {
    .content-area {
      line-height: 1.6em;
    }
}
IAmNotABear
  • 101
  • 4
  • I do believe the second code is cleaner as well , you'll need to listen to an event before executing the first code, and the second doesn't rely on javascript , thank you – Mike s Mar 20 '15 at 19:22
  • Your welcome, also the CSS solution keeps your styling where it belongs. In the CSS and not in the JavaScript files. – IAmNotABear Mar 20 '15 at 20:48