John O John O - 1 month ago 7
jQuery Question

Passing a variable to init function (variable scope issue)

I'm using stellar.js for a parallax image effect. I'm trying to pass a variable to the stellar.js init function but it's not working. The plugin is initialized in my $(document).ready() function (NOT a requirement) where I also do a bit of math because I can't hardcode the numbers when I initialize stellar.js. Here's the code in question.

$(document).ready(function() {
var $height = $("img").height(); // i.e. $height = 1000px
var $offset = $height * .75; // i.e. $offset = 750px;

$(window).stellar({
horizontalScrolling: false,
verticalOffset: $offset
});

)};


If I just put in 750 as the verticalOffset in the stellar init function it works fine. However, using the $offset variable does not work as it seems to be out of scope of the $(window).stellar() function. Can anyone help me out with this? Any help is greatly appreciated.

Answer

Have you tried to put a break point into a stellar.js file code to see what options are passed there during initialization (actually, I got the same value I'd passed)? If you think, the problem with a scope, maybe you should try something like that:

$(window).stellar({
      horizontalScrolling: false,
      verticalOffset: $("img").height() * .75
    });

By the way, there is a misprint in your code, as it should be }); instead of )}; at the end

Comments