Change (Add/Remove) CSS Class On Mobile With JS or jQuery

Viewed 5431

How can I change ten on desktop to three on mobile with JS or jQuery or SemanticUI?

<div class="ui ten column grid">...</div>

If screen size is less than 700px, change ten to three.

3 Answers

You could use $(window).width() < 700 and check if width < 700 then removeClass ten and addClass three.

This function will run even if you resize you window manually via mouse.

//Resize window
function resize() {
  if ($(window).width() < 700) {
    $('.myDiv').removeClass('ten').addClass('three');
  }
}

Runable Example:

//Resize window
function resize() {
  if ($(window).width() < 700) {
    $('.myDiv').removeClass('ten').addClass('three');
  }
}

//watch window resize
$(window).on('resize', function() {
  resize()
});
.ten {
  background: green;
}

.three {
  background: red;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="ui ten column grid myDiv">My Div</div>

Try this code for JQuery:

if ($(window).width() < 700) {
$("...").removeClass("ten");
$("...").addClass("three");
} else {
$("...").removeClass("three");
$("...").addClass("ten");
}

Use this example

if ( window.innerWidth < 700 ) {
    document.querySelector("div").classList.add('three');
    document.querySelector("div").classList.remove('ten');
}
Related