Sami Al-Subhi
Sami Al-Subhi

Reputation: 4672

Can not access global variables inside a jQuery event handler

I am using the following code to track the scrolling and I want to put the selected element variables outside the event handler so they are not called each time the user scrolls thereby saving resources. The following only works if I put the first two variables inside the event handler:

    var recommend_con_list=$(".recommend_con_list")
    var recommend_con=$('.recommend_con')
    $(window).scroll(function () {

        var y=$(window).scrollTop()
        if(y > 82){
            recommend_con.css({position:"fixed",top:"0"})
        }else{
            recommend_con.css({position:"",top:""})
        }
    });

Upvotes: 2

Views: 2111

Answers (1)

Ian
Ian

Reputation: 50905

If you want to optimize further, I would use this:

$(document).ready(function () {
    var recommend_con_list = $(".recommend_con_list").get(),
        recommend_con = $('.recommend_con').get(),
        $window = $(window);

    $window.scroll(function () {
        var y = $window.scrollTop();
        if (y > 82) {
            for (var i = 0, j = recommend_con.length; i < j; i++) {
                recommend_con[i].classList.add("special");
            }
        } else {
            for (var i = 0, j = recommend_con.length; i < j; i++) {
                recommend_con[i].classList.remove("special");
            }
        }
    });
});

With this CSS:

<style type="text/css">
    .special {
        position: fixed;
        top: 0;
    }
</style>

Upvotes: 1

Related Questions