i7nvd
i7nvd

Reputation: 1318

How do I set initial CSS values with JavaScript on load?

I'm really new to JavaScript, and I'm still trying to learn a lot. I found a snippet that allows for horizontal parallax on scroll. I'm using the following code to set the 'right' css property:

var $horizontal = $('.scroll');

    $(window).scroll(function () {
    var s = $(this).scrollTop(),
        d = $(document).height(),
        c = $(this).height();

    scrollPercent = (s / (d - c));

    var position = (scrollPercent * 2500) + ($(document).width() / 2);

    $horizontal.css({
        'right': position
    });
});

This works really well once the scroll happens, however, on the load, the 'right' property is, by default, set to 0. It only snaps to my position variable once I start scrolling. How can I call this variable on load and have it modify with scroll?

Upvotes: 0

Views: 215

Answers (1)

dave
dave

Reputation: 64657

Just call the scroll function when the window is finished loading:

$(window).scroll(function () {
    ...
});

$( window ).load(function() {
   $(window).trigger('scroll');
});

Upvotes: 1

Related Questions