Monstr92
Monstr92

Reputation: 404

How can I run a jQuery animation only once on scroll?

I'm trying to use Javascript to detect when a user scrolls down past a certain height on my site, and that then my "social" icons fade in once they reach that scroll breakpoint.

The thing I'm trying to figure out is how can I only run the fadeTo once the alpha hits 1 and lock it in? So that when the user scrolls up and down again the fadeIn doesn't happen again over and over unless they initiate a page reload which would reset everything.

//SCROLL
$(window).on("scroll", function () {
//SOCIAL ICONS
if ($(this).scrollTop() > 1750) {
    $(".img-social .gith").stop(true).fadeTo(250, 1);
    $(".img-social .inst").stop(true).fadeTo(450, 1);
    $(".img-social .twit").stop(true).fadeTo(650, 1);
    $(".img-social .drib").stop(true).fadeTo(850, 1);
    $(".img-social .link").stop(true).fadeTo(1050, 1);
} else {
    $(".img-social .gith").stop(true).fadeTo(10, 0);
    $(".img-social .inst").stop(true).fadeTo(10, 0);
    $(".img-social .twit").stop(true).fadeTo(10, 0);
    $(".img-social .drib").stop(true).fadeTo(10, 0);
    $(".img-social .link").stop(true).fadeTo(10, 0);
}
});

Thanks

Upvotes: 4

Views: 5710

Answers (2)

The Alpha
The Alpha

Reputation: 146191

Just put following code within your first if condition to off the scroll event once you run the code:

$(window).on("scroll.socialIcon", function () {
    if ( $(this).scrollTop() > 1750 ) {
        // ...
        $(window).off("scroll.socialIcon"); // last line
    } else {
        //...
    }
});

So the scroll.socialIcon (namespaced) event won't response anymore.

Upvotes: 2

eriese
eriese

Reputation: 175

use a boolean to record whether it's happened or not:

// SET BOOLEAN
var scrolled = false;

//SCROLL
$(window).on("scroll", function () {
//SOCIAL ICONS
    if ($(this).scrollTop() > 1750 && !scrolled) {
        $(".img-social .gith").stop(true).fadeTo(250, 1);
        $(".img-social .inst").stop(true).fadeTo(450, 1);
        $(".img-social .twit").stop(true).fadeTo(650, 1);
        $(".img-social .drib").stop(true).fadeTo(850, 1);
        $(".img-social .link").stop(true).fadeTo(1050, 1);
        scrolled = true;
    } else {
        $(".img-social .gith").stop(true).fadeTo(10, 0);
        $(".img-social .inst").stop(true).fadeTo(10, 0);
        $(".img-social .twit").stop(true).fadeTo(10, 0);
        $(".img-social .drib").stop(true).fadeTo(10, 0);
        $(".img-social .link").stop(true).fadeTo(10, 0);
        scrolled = false;
    }
});

Upvotes: 3

Related Questions