jgb jgb - 7 months ago 24
Javascript Question

How to add setTimeout to OnClick function Show/Hide with multiple divs

I have an onClick function that's show/hiding multiple divs depending on which div you click on. How can I get this to run automatically with a timer, changing every 5 seconds, as well as working with onClick? Any suggestions are welcome, thanks!

$(document).ready(function($){

$('.showSection').on('click', function () {
$(this).addClass('selected').siblings().removeClass('selected');
$('.targetSection').hide();
$('#div' + $(this).data('target')).show();
});
$('.showSection').first().click();
});


Here's a fiddle:
https://jsfiddle.net/8qw05um1/

Answer

Try this, it will loop through the divs but also allow you to click to change. Since I broke out your click function into one that can be used for the click or the interval, you can change it if you want different behavior.

$(document).ready(function($){

  var options = $.makeArray( $('.showSection') );

  function doStuff() {
    var that;
    if (this === window) {
      that = options[0];
      options.push(options.shift());
    } else {
      that = this;
    }

    $(that).addClass('selected').siblings().removeClass('selected');
    $('.targetSection').hide();
    jQuery('#div' + jQuery(that).data('target')).show();
  }

  $('.showSection').on('click', doStuff); 

  setInterval(doStuff, 5000);

  $('.showSection').first().click();
});