Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic Javascript when changing screen size

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?

like image 770
themich Avatar asked Jun 08 '15 13:06

themich


People also ask

How to get screen size using JavaScript?

Use window. innerWidth and window. innerHeight to get the current screen size of a page.

How do I resize my screen to fit CSS?

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.


3 Answers

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 */
}
like image 193
Halcyon Avatar answered Oct 16 '22 16:10

Halcyon


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

like image 23
Narendrasingh Sisodia Avatar answered Oct 16 '22 18:10

Narendrasingh Sisodia


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
    }
}
like image 21
oshell Avatar answered Oct 16 '22 17:10

oshell