0

I have this function for cycling through tabs:

function CycleTabs() {
  //cache a reference to the tabs
  var tabs = jQuery('.shapedo-tabs .single-tab');
  //auto-rotate every 5 seconds
  setInterval(function() {
    //get currently-on tab
    var onTab = tabs.filter('.activetab');
    //click either next tab, if exists, else first one
    var nextTab = onTab.index() < tabs.length - 1 ? onTab.next() : tabs.first();
    nextTab.addClass("activetab");
    jQuery(".single-tab").not(nextTab).removeClass("activetab");
    var forTabCycle = jQuery(nextTab).attr("for");
    jQuery(".stab-content#" + forTabCycle).addClass("activecontent");
    jQuery(".stab-content").not("#" + forTabCycle).removeClass("activecontent");
  }, 5000);
}

CycleTabs();

I also have a function for what happens when the user clicks on the tab:

  jQuery(".single-tab").click(function() {
    var forTab = jQuery(this).attr("for");
    jQuery(this).addClass("activetab");
    jQuery(".single-tab").not(this).removeClass("activetab");
    jQuery(".stab-content#" + forTab).addClass("activecontent");
    jQuery(".stab-content").not("#" + forTab).removeClass("activecontent");
  });

How can I make the cycle stop when the user clicks on the tab? e.g - I need that once the user clicks on the tabs the cycle stops.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339

1 Answers1

2

You can set a timer variable, then use that variable to clear the interval.

    var cycle_timer;

    function CycleTabs() {
      //cache a reference to the tabs
      var tabs = jQuery('.shapedo-tabs .single-tab');
      //auto-rotate every 5 seconds
      cycle_timer = setInterval(function() {
        //get currently-on tab
        var onTab = tabs.filter('.activetab');
        //click either next tab, if exists, else first one
        var nextTab = onTab.index() < tabs.length - 1 ? onTab.next() : tabs.first();
        nextTab.addClass("activetab");
        jQuery(".single-tab").not(nextTab).removeClass("activetab");
        var forTabCycle = jQuery(nextTab).attr("for");
        jQuery(".stab-content#" + forTabCycle).addClass("activecontent");
        jQuery(".stab-content").not("#" + forTabCycle).removeClass("activecontent");
      }, 5000);
    }

    CycleTabs();

      jQuery(".single-tab").click(function() {
        var forTab = jQuery(this).attr("for");
        jQuery(this).addClass("activetab");
        jQuery(".single-tab").not(this).removeClass("activetab");
        jQuery(".stab-content#" + forTab).addClass("activecontent");
        jQuery(".stab-content").not("#" + forTab).removeClass("activecontent");
        clearInterval(cycle_timer);
      });
imvain2
  • 15,480
  • 1
  • 16
  • 21