Removing the CSS class according to screen resolution

Asked

Viewed 44 times

1

I am trying to remove a CSS class by Javascript when the screen decreases

Only the event I’m wearing is the scroll, which is for mouse scrolling. Then every time the screen decreases need to scroll the mouse to function.

Does anyone know an own event for resolution in Javascript?

jQuery(function () {
                
    jQuery(window).scroll(function () {
    
      if (jQuery(this).width() < 1200) {        
         $("#divtexto").removeClass("col-6");      
         $("#textMaratona").removeClass("col-6");       
      }else{       
         $("#divtexto").addClass("col-6");     
         $("#textMaratona").addClass("col-6");   
     } 
        
   });
       
  });

2 answers

2

You must use the event resize for this. See the documentation of Handler jQuery.

Thus:

$(function() {
  $(window).resize(function() {
    if ($(this).width() < 1200) {
      $('#example').removeClass('custom');
    } else {
      $('#example').addClass('custom');
    }
  });
});
#example.custom {
  color: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<div id="example">Olá, mundo!</div>

  • vlw msm kara.. worked here kkkk muit obg...

1

Could use both events at the same time using the method .on():

$(window).on("scroll resize", function () {

Just put the events separated by a space as shown above.

But it doesn’t make much sense to use the event scroll, since it has nothing to do with the width of the window. Use only the event resize:

$(window).on("resize", function () {

And you can even simplify the code using a ternary, if it’s just to do this, adding/removing the class of the two elements at the same time:

$(function () {
   $(window).on("resize", function () {
      $("#divtexto, #textMaratona")
      [(jQuery(this).width() < 1200 ? "remove" : "add") + "Class"]
      ("col-6");      
   });
});

Why use JQuery if you can use the alias $? Saves some bytes of code.

  • I tested it that way too.. and it worked.. vlw kara..

  • Mark one of the answers with ✔.

Browser other questions tagged

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