peter vries February 2016

Run script upon scroll, but only once

I'm using IntroJS on my website. People can start the tour by clicking my button, but I want it to auto-start when visitors scroll down. I made this function for this, but it keeps starting the tour thus flipping the entire webpage out:

window.onscroll = function() {tourstart()};

function tourstart() {
    if (document.body.scrollTop > 50) {
        introJs().start();
}
}

How can I only make it run once?

Thank you in advance!

Answers


Barmar February 2016

Remove the handler when you start the tour:

function tourstart() {
    if (document.body.scrollTop > 50) {
        window.onscroll = null;
        introJs().start();
    }
}


Andrew February 2016

You wrote tag jQuery, so if you use it, you can just write:

$(window).one('scroll', function() {
  tourstart();
});


Baro February 2016

If you want run once after page load try this:

var onlyOnce = true;
window.onscroll = function() {tourstart()};

function tourstart() {
    if (document.body.scrollTop > 50 && onlyOnce) {
        onlyOnce = false;
        introJs().start();
    }
}

But if you want run once for user(/browser), you can use the cookies, here an other stackoverflow solution for use the cookies but copy/paste the functions here:

The code change in this way :

var onlyOnce = readCookie("once");
window.onscroll = function() {tourstart()};

function tourstart() {
    if (document.body.scrollTop > 50 && onlyOnce!="true") {
        createCookie("once", "true", 10); // It expires in 10 days for example
        introJs().start();
    }
}

function createCookie(name,value,days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime()+(days*24*60*60*1000));
        var expires = "; expires="+date.toGMTString();
    }
    else var expires = "";
    document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for(var i=0;i < ca.length;i++) {
        var c = ca[i];
        while (c.charAt(0)==' ') c = c.substring(1,c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
    }
    return null;
}

Post Status

Asked in February 2016
Viewed 3,104 times
Voted 6
Answered 3 times

Search




Leave an answer