Search code examples
javascriptjqueryzurb-foundationcycle

Cycle tabs with .click() and setInterval


I have tried this so many different ways now and have yet to have any kind of progress or success. I'm using the foundation 5 framework and am trying to get a set of tabs to cycle active automatically. Here is a link. Since more than just the active class changes on click I figured it would be easier to emulate a click rather than addClass(active)among other things. Here is what I'm working with currently.

HTML:

<dl class="tabs" datatab>
  <dd class="active">
    <a href="efs-tabpane-1-0>Promote</a>
  </dd>
  <dd class>
    <a href="efs-tabpane-1-1>Educate</a>
  </dd>
  <dd class>
    <a href="efs-tabpane-1-2>Analyze</a>
  </dd>
  <dd class>
    <a href="efs-tabpane-1-3>Report</a>
  </dd>
</dl>

JS:

$( "dd a" ).addClass("cycle");

setInterval(function(){
  $(this).next("a.cycle").click(), console.log("test");
}, 3000);

The console logs the message correctly but literally nothing else happens. Any help appreciated. Thanks.


Solution

  • this in your example is window. You also don't need to add a .cycle class. You can use a sibling selector to find the next element.

    setInterval(function(){
      $(".tabs .active + dd a").click();
    }, 3000);
    

    Though if you want it to loop around, you need to select the first one when you reach the end. You could do this:

    setInterval(function(){
      if($(".tabs .active + dd a").length){
        $(".tabs .active + dd a").click();
      }else{
        $(".tabs dd:first a").click();
      }
    }, 3000);