Danin Na
Danin Na

Reputation: 409

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 ?

Upvotes: 1

Views: 169

Answers (5)

Nikhil Aggarwal
Nikhil Aggarwal

Reputation: 28445

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 );
});

Upvotes: 1

rrk
rrk

Reputation: 15846

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(){});.

Upvotes: 1

kazimt9
kazimt9

Reputation: 563

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

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

Upvotes: 1

Alex Kolarski
Alex Kolarski

Reputation: 3425

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.

Upvotes: 4

Remy Grandin
Remy Grandin

Reputation: 1686

I would suggest that :

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

Upvotes: 1

Related Questions