简体   繁体   中英

improve $(document).ready and $( window ).resize and make it more compact

I have this code for example

var Wwin = $(window).width()

if ( Wwin > 2000 ) { 
    alert ('yes')
} else {    
    alert ('no')    
}

I need this code run , every time $(document).ready and $( window ).resize

for example

$( window ).resize(function() {

    var Wwin = $(window).width()

    if ( Wwin > 2000 ) { 
        alert ('yes')
    } else {    
        alert ('no')    
    }

});

$(document).ready(function() {

    var Wwin = $(window).width()

    if ( Wwin > 2000 ) { 
        alert ('yes')
    } else {    
        alert ('no')    
    }

});

is there any way to improve this code and make it more compact ?

for example

var $MyFunction =  (   var Wwin = $(window).width()
                       if ( Wwin > 2000 ) { 
                            alert ('yes')
                       } else { 
                            alert ('no')    
                       }  )

$( window ).resize(function() {

     $MyFunction

}); 

$(document).ready(function() {

     $MyFunction

});

or

$(document).ready(function(){} & $( window ).resize(function() {

         $MyFunction

});

What do u suggest ?

You can always make a function.

var windowSize = function () {
    if ( $(window).width() > 2000 ) { 
        alert('yes')
    } else {    
        alert('no')    
    }
}
$(document).ready(windowSize);
$(window).resize(windowSize);

But keep in mind that resize event will be fired many times.

I would suggest that :

var $MyFunction = function(){alert ($(window).width() > 2000?'yes':'no')};
$( window ).resize($MyFunction); 
$(document).ready($MyFunction);
var resizeHandler = function () {
    if ( $(window).width() > 2000 ) alert('yes');
    else alert('no');
}

$(function() {
    resizeHandler();
    $(window).resize(resizeHandler);
});

I made an edit I think that is the answer you need.

var $windowSize = function () {
    if ( $(window).width() > 2000 ) { 
        alert('yes')
    } else {    
        alert('no')    
    }
}
$(document).on('ready',$windowSize);
$(window).on('resize',$windowSize);

Why you should use on()
It makes more sense to use $(document).on('ready', function(){}); and $(window).on('resize', function(){}); .

You just need to create a function and call it on load and bind it to window resize event.

var resizeView = function () {
    if ( $(window).width() > 2000 ) {
        alert('yes');
    } else {
        alert('no')
    }
}

$(document).ready(function() {
    resizeView();
    $(window).resize(resizeView );
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM