Jacques Bronkhorst
Jacques Bronkhorst

Reputation: 1695

Javascript $window is not defined when adding paralax scrolling

I am currently building a time line based page with the different years, as this is a single page with a lot of info, I decided to go with the paralax scrolling effects available, to construct my page to work in the following manner:

enter image description here

I have added paralax scrolling based on this tutorial. But it does not function the way I want to.

I have created this Fiddle to try and demonstrate what I want it to do.

I use the same JS as in the tutorial:

 $(document).ready(function () {
        $('section[data-type="background"]').each(function () {
            var $bgobj = $(this); // assigning the object

            $(window).scroll(function () {
                var yPos = -($window.scrollTop() / $bgobj.data('speed'));

                // Put together our final background position
                var coords = '50% ' + yPos + 'px';

                // Move the background
                $bgobj.css({ backgroundPosition: coords });
            });
        });
    });

But keep on getting the following message when scrolling through the page: Uncaught ReferenceError: $window is not defined Any advice or assistance would be greatly appreciated.

Upvotes: 3

Views: 17496

Answers (3)

Seer
Seer

Reputation: 739

correct the $window to $(window)

Upvotes: 8

palaѕн
palaѕн

Reputation: 73896

Try this:

$(document).ready(function () {

    // Cache the Window object
    $window = $(window);

    $('section[data-type="background"]').each(function () {
        var $bgobj = $(this); // assigning the object

        // Use the cached window object here
        $window.scroll(function () {

            // Use the cached window object here
            var yPos = -($window.scrollTop() / $bgobj.data('speed'));

            // Your code here
        });
    });
});

FIDDLE DEMO

Upvotes: 4

Fabien Sa
Fabien Sa

Reputation: 9470

You can declare a new variable outside the .scroll

...
var $window = $(window);
$window.scroll(function () {
...

(beacause you use the $window variable inside the .scroll)

Upvotes: 3

Related Questions