I have a div class where I want change the css class name when resolution of the user's screen changes. The following script works:
if ( $(window).width() < 739) {
$("#default").toggleClass('classold classnew');
}
else {
$("#default").toggleClass('classold classold');
}
But it has a problem. When I open a browser with a width of 600px and change it to full screen, the mobile class version is not updated. It only works when I reload the page.
How can I make this work without reloading the page?
Use window. innerWidth and window. innerHeight to get the current screen size of a page.
Using CSS, you can set the background-size property for the image to fit the screen (viewport). The background-size property has a value of cover . It instructs browsers to automatically scale the width and height of a responsive background image to be the same or bigger than the viewport.
Move this code into a resize handler:
function resize() {
if ( $(window).width() < 739) {
$("#default").toggleClass('classold classnew');
}
else {
$("#default").toggleClass('classold classold');
}
}
$(window).on("resize", resize);
resize(); // call once initially
You can also consider using CSS3 media queries:
@media screen and (max-width: 739px) {
/* rules for small screens */
}
@media screen and (min-width: 740px) {
/* rules for large screens */
}
You can simply achieve it using CSS as
<style>
@media (max-width: 600px) {
/* your code */
}
@media (min-width: 740px) {
/* your code */
}
</style>
CSS media queries
Why your script does't work
Your if-else statement will be called on site load and then will never be touched again. For it to work properly you would have to trigger it on a resize event.
Why you should not use this solution
Whenever you can solve something with CSS only you should avoid using Javascript. One reason is performance, but there are also edge cases where using Javascript instead of CSS can result in strange behaviour. For example when you use the maximize function of the browser and get the new window size right after this can result in wrong results.
How you should solve the problem
@media screen and (max-width: 739px) {
#default{
//css rules for smaller screens
}
}
@media screen and (min-width: 740px) {
#default{
//css rules for larger screens
}
}
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