开发者

reset variables after browser resized using jquery

开发者 https://www.devze.com 2023-03-18 21:51 出处:网络
I\'m trying to create a jquery function that can be called both on ready and when the browser window is resized.

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

});

Bu开发者_Go百科t 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 within setWidth, 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.

jQuery(document).ready(function ($) {
    var windowWidth, boxWidth, paddingWidth; // declare variables in this scope

    function setWidth() {
        windowWidth = $(window).width(); // set variables in this scope
        boxWidth = $('#addbox').width();
        paddingWidth = (windowWidth - boxWidth) / 2;
    };

    setWidth(); // just call the function

    $(window).resize(setWidth);

    $(".scroll").click(function (event) {
        event.preventDefault();
        $('html,body').animate({
            scrollLeft: $(this.hash).offset().left - paddingWidth
        }, 750);
    });
});

Note that $(setWidth) is an odd call, and a relatively expensive one. It says "call setWidth when the document is ready". Since you are in a jQuery(document).ready handler, you can be sure that that is true. You can just execute the function with setWidth().


Try this

jQuery(document).ready(function($) {

var paddingWidth = 0;

function setWidth() {
    var windowWidth = $(window).width();
    var boxWidth = $('#addbox').width();
    paddingWidth = (windowWidth - boxWidth) / 2;
};

$(setWidth);

$(window).resize(setWidth);

$(".scroll").click(function(event){     
    event.preventDefault();
    $('html,body').animate({scrollLeft:$(this.hash).offset().left-paddingWidth}, 750);
});
0

精彩评论

暂无评论...
验证码 换一张
取 消