Reloading Javascript or JQuery page, why?

Why does Javascript or jQuery require a page reload before applying certain effects?

CSS is real-time updates

Example:

It works in real time

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

      

Requires a page reload to see the effect, do not refresh the resize window in real time

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

      

Why?

+3


source to share


5 answers


Because this is the last JavaScript. It is currently a routine that only runs once when the script tag is parsed. You can wrap it in a function and run it multiple times. For example, on a window resize event. The first is CSS, and browsers constantly 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 every time the window is resized.

+3


source


This is because jQuery / Javascript is executed on load and not when the window is resized. The CSS is theoretically also executed on load and just knows what to display when.

If you want to run JS / jQuery on window resize, you need to add something like this:

window.onresize = resize;

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

      



The above code snippet will run every time the window is resized and hence check every time it runs if the window is larger than 980.

More about .onresize

+1


source


This will work if the event is resize

fired

  $( window ).resize(function() {
     if ($(window).width() > 980) {
       ... 
        .....
        ....
    }
 });

      

This will work

ref - resize () in jquery

+1


source


You need to fire an event to do javascript validation for that condition without loading the page

window.onresize = function(event) {
    // add your if condition here
};

      

for jquery just use below

$(window).resize(function() {
    // add you if condition here
});

      

+1


source


$(window).width()

      

When you call a function like this, you get the return value when it is executed. If you want to assign a value when resizing, click click, etc., you must add an event listener.

$(window).on('resize', function() {

    console.log( $(window).width() )

});

      

+1


source







All Articles