Search code examples
javascriptjquerycssmedia-queriesreal-time

Javascript or JQuery need page reload, Why?


Why does Javascript or jQuery need a page reload before it applies certain effects?

CSS is updates in real-time

Example:

This works in real time

@media all and (max-width:767px) {
.nav-menu {
 margin:0px!important;
 }
 }

This needs a page reload to see the effect, don't update on resize window in real time

if ($(window).width() > 980) {
do something
};

Why?


Solution

  • Because that latter is JavaScript. Currently it's a routine that is fired only once on when the script tag is parsed. You can wrap it in a function and fire it multiple times. For example on a window resize event. The former is CSS and browsers continually update the page according to the CSS rules.

    window.addEventListener("resize", function(){
         if ($(window).width() > 980) {
             do something
         };
    }, false);
    

    Or in jQuery:

    $(window).on("resize", function(){
         if ($(window).width() > 980) {
             do something
         };
    });
    

    Now this will fire everytime the window is resized.