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?
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?
You can use the "resize" event :
$( window ).resize(function() {
if ($(window).width() < 700 ) {
$('.one').addClass('two').removeClass('one');
} else {
$('.two').addClass('one').removeClass('two');
}
});
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.
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" );
}
});
You can use:
$( window ).resize(function() {
if ($(window).width() <= 700)
$('.one').addClass('two').removeClass('one')
else
$('.two').addClass('one').removeClass('two')
}).trigger('resize');
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');
}
}
});