0

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!

peter vries
  • 155
  • 1
  • 15

3 Answers3

3

Remove the handler when you start the tour:

function tourstart() {
    if (document.body.scrollTop > 50) {
        window.onscroll = null;
        introJs().start();
    }
}
Barmar
  • 596,455
  • 48
  • 393
  • 495
  • exactly what I needed, thank you! Small addition, maybe you know this one too: can I 'force' them to an anchor too, within the same script? Thanks a bunch!! – peter vries Feb 08 '16 at 19:52
1

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

$(window).one('scroll', function() {
  tourstart();
});
Andrew
  • 124
  • 5
1

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;
}
Community
  • 1
  • 1
Baro
  • 3,875
  • 2
  • 12
  • 31