muszynov
muszynov

Reputation: 329

Call JS function only once for window scroll

I have a function that writes text (typewriter effect) when user scrolls to specific section. But I want to do it only once. So if user scrolls first time the text is written and that should be all. But If user scrolls again (doesn't matter in which direction) the function is called again so the text is being typed again and again... Here's the JS code:

var counter = 0;
$(window).on('scroll', (function () {
    counter ++;
    if(counter < 80){
        if ($(window).scrollTop() >= $('#anchor-form').offset().top - 200) {
            $(window).scrollTop();
            $('.form__icon').addClass('form--animate');
            showText("Some Text to be written", 0);
        }
    }
}));

function showText(msg, x) {
    if (x < msg.length) {
        $txt_form.html(msg.substring(0, x+1));
        x++;
        setTimeout(function() {
            showText(msg,x)
        }, 50)
    }
};

As You can see I've prevented it by setting counter. I've checked how many 'counts' would it be when window is scrolled to this section and just set the value inside the IF statement. But I feel that this is not sufficient and 'good practice' method. Sometimes the text is glitchy besides this prevention method. I've tried with jQuery .one() method also but it doesn't work.

I'll appreciate any suggestions.

Upvotes: 0

Views: 77

Answers (1)

Ali
Ali

Reputation: 458

get a second counter inside your if statement and and set it to counter2++ then in your if statement check the count2 === 1

Upvotes: 1

Related Questions