0

There is a page I'm working on. When a user scrolls down to the tabs ("Existing workflow" and "KBCT workflow"), I'd like to change an "Existing workflow" tab to a "KBCT workflow" one with a 5-second delay only. This need to be executed only when the tabs are visible (user scrolled to that position).

Here is the code

tabs = jQuery('#kbct-tabs');
kbctTab = tabs.find('.tab:last-child');

if (tabs.css('visibility') === 'visible') {
  setTimeout(function() {
    kbctTab.click();
    console.log('executed');
  }, 5000);
}

And I don't know what's wrong with it, particulary the if statement. It works, but not how it's supposed to. It seems like the browser ignores the if statement and starts to count 5 seconds after the page has loaded, not when a user has scrolled to the tabs. BUT when I write that if statement in the Chrome Console, it works like it's supposed to.

Here is a screenshot.

Can you please tell me what is wrong?

avramch
  • 19
  • 1
  • 4

2 Answers2

2

Your code is working 100%.

You just need to change 2 things:

1 - Add an scroll event listener (element.scroll(callback))

2 - Use the scrollTop property to check visibily. (element.scrollTop())

 var kbctworkflow = function () {
    var tabs = jQuery('#kbct-tabs');
    var kbctTab = tabs.find('.tab:last-child');
    if ($(document.body).scrollTop() > tabs.offset().top - 300) {
      setTimeout(function() {
        kbctTab.click();
        console.log('executed');
      }, 1000);
    }
  };
  $(window).scroll(kbctworkflow);

DEMO http://jsbin.com/qatice/2/edit?js,output

rafaelcastrocouto
  • 11,781
  • 3
  • 38
  • 63
-1

try using jquery's is selector.

tabs = jQuery('#kbct-tabs');
kbctTab = tabs.find('.tab:last-child');

if (tabs.is(':visibile')) {
  setTimeout(function() {
    kbctTab.click();
    console.log('executed');
  }, 5000);
}
  • Didn't help :( It starts to count 5 seconds when the page has loaded, not when tabs become visible – avramch Oct 01 '16 at 21:19
  • Why the down vote? You could have just emphasized that I missed the "This need to be executed only when the tabs are visible (user scrolled to that position)" part. –  Jun 01 '18 at 16:25