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
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
Share Improve this question edited Sep 2, 2015 at 7:28 Tushar 87.2k21 gold badges163 silver badges181 bronze badges asked Sep 1, 2015 at 6:46 PerspolisPerspolis 8623 gold badges11 silver badges28 bronze badges 2- Initial painting is a different Event then resize. You could extract the logic into a function and bind it to resize as well as document.ready. – flaschenpost Commented Sep 1, 2015 at 6:49
- Check my answer and fiddle in the below. It is the simplest way of doing that – Rajesh kannan Commented Sep 1, 2015 at 6:52
3 Answers
Reset to default 7Use 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();
});
DEMO
Use media Query
Use the following Css
.yellow{
background:yellow;
}
@media (max-width:500px) {
.yellow {
background:red;
}
}
Check the folowing fiddle
http://jsfiddle/adxg3079/
Let me know if it is helpful