Reputation: 231
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/
Upvotes: 0
Views: 275
Reputation: 4336
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();
});
Upvotes: 1
Reputation: 10083
$(document).ready(function(){
$('.showSection').on('click', function (e) {
if( typeof showHideInterval != "undefined" )
{
clearInterval( showHideInterval );
}//if
var $this = $(this);
showHideDivs( $this );
showHideInterval = setInterval( showHideDivs, 2000, $this );
});
$('.showSection').first().click();
});
function showHideDivs( $this )
{
$this.addClass('selected').siblings().removeClass('selected');
$('.targetSection').hide();
$('#div' + $this.data('target')).show();
}//showHideDivs()
Upvotes: 1