Reputation: 409
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
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
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
Reputation: 563
var resizeHandler = function () {
if ( $(window).width() > 2000 ) alert('yes');
else alert('no');
}
$(function() {
resizeHandler();
$(window).resize(resizeHandler);
});
Upvotes: 1
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
Reputation: 1686
I would suggest that :
var $MyFunction = function(){alert ($(window).width() > 2000?'yes':'no')};
$( window ).resize($MyFunction);
$(document).ready($MyFunction);
Upvotes: 1