I’m trying to create a jquery function that can be called both on ready and when the browser window is resized.
jQuery(document).ready(function($) {
function setWidth() {
var windowWidth = $(window).width();
var boxWidth = $('#addbox').width();
var paddingWidth = (windowWidth - boxWidth) / 2;
};
$(setWidth);
$(window).resize(setWidth);
$(".scroll").click(function(event){
event.preventDefault();
$('html,body').animate({scrollLeft:$(this.hash).offset().left-paddingWidth}, 750);
});
});
But that code doesn’t seem to be working, firebug says that paddingWidth isn’t defined. What am I doing wrong?
Variables have the scope in which they were defined (using
var). In your case, this means that they are only defined withinsetWidth, and are re-initialised on each execution of that method.You should move them into a containing scope so that functions in descendant scopes have access to their values.
Note that
$(setWidth)is an odd call, and a relatively expensive one. It says “callsetWidthwhen the document is ready”. Since you are in ajQuery(document).readyhandler, you can be sure that that is true. You can just execute the function withsetWidth().