I have this jQuery code for add
remove
class using jQuery
in resize window:
JS:
$(function () {
$(window).bind("resize", function () {
console.log($(this).width())
if ($(this).width() < 500) {
$('div').removeClass('yellow').addClass('red')
} else {
$('div').removeClass('red').addClass('yellow')
}
})
})
HTML:
<div style="width:300px; height:100px;" class="yellow"></div>
In action, This worked only when i manualy resize window But in default if device window < 500 this function not work.
how do fix this ?!
Demo HERE
Use trigger()
to run function on page load
Execute all handlers and behaviors attached to the matched elements for the given event type.
$(window).bind("resize", function () {
console.log($(this).width())
if ($(this).width() < 500) {
$('div').removeClass('yellow').addClass('red')
} else {
$('div').removeClass('red').addClass('yellow')
}
}).trigger('resize');
Demo
You can also use CSS media
queries to set the style properties of elements on page load. This will have little performance gain and better user experience than using Javascript.
@media (max-width: 500px) {
div {
color: red;
}
}
@media (min-width: 500px) {
div {
color: yellow;
}
}
Try to invoke the resize
event once when the DOM got ready,
$(function(){
$(window).bind("resize",function(){
if($(this).width() <500){
$('div').removeClass('yellow').addClass('red')
}
else{
$('div').removeClass('red').addClass('yellow')
}
}).resize();
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With