So I am trying to read some jQuery that was written by my organization some years ago. I’m not very proficient with jQuery (but I’m okish with Javascript). I’m trying to prevent the slide from rotating to the next slide if a user hovers over it.
Here’s the first part of the code, I think all it is determining is where and how the slide should be appearing. I think it also says that the slide will switch every 7 seconds.
var current_slide_index = 0; //The index of the slide being displayed;
var timer; //the timer counting the delay to the transition
var time_delay = 7000;
$(document).ready( function() {
$('.pane:first').addClass('current');
if (!$.support.opacity) $('.panes .pane').not('.current').hide();
$('.tabs a').click( function(e) {
e.preventDefault();
var triggers = $('.tabs a');
current_slide_index = triggers.index($(this));
showSlide();
});
});
function showSlide() //Show the slide indicated by current_slide_index
{
var triggers = $('.tabs a');
triggers.removeClass('current').eq(current_slide_index).addClass('current');
var old_slide = $('.panes .pane.current');
if (!$.support.opacity) {
old_slide.children().fadeOut(500, function() {
old_slide.removeClass('current').hide();
$('.panes .pane').eq(current_slide_index).addClass('current').show().children().fadeIn(300);
});
} else {
old_slide.removeClass('current').fadeOut(500, function() {
$('.panes .pane').eq(current_slide_index).addClass('current').fadeIn(300);
});
}
clearTimeout(timer);
timer = setTimeout('rotateSlide()',time_delay);
}
I believe this is the section I have to stop – can I do it by setting some sort of conditional that determines whether or not I am hovering over the slide in question? This is where my lack of jQuery knowledge hurts me – I haven’t the foggiest how to how to stop the slider.
function rotateSlide() //move the slide to the next one
{
//calculate the next index
var triggers = $('.tabs a');
//wrap to index zero if necessary
current_slide_index = (current_slide_index + 1) % triggers.length;
//Now show the new slide
showSlide();
}
timer = setTimeout('rotateSlide()',time_delay);
So my questions are, can anyone interpret this code for me in a clearer manner, and is there a way to prevent the slider from sliding if you hover over it?
From what I can tell, I could just select #slider and use something like (this is pseudocode)
if ($("slider").hover) {
blah blah blah thing that prevents slide from rotating
}
else {
code that allows rotating
}
Your understanding of the code is quite accurate. In order to implement the feature you want, I would do a couple of things. First, move the timer code into a pair of functions like this:
Next, put the call to
showNextSlideIn()at the bottom ofshowSlide, where you just removed the clearTimeout/setTimeout lines.Finally, add the behaviour for hovering, above your function definitions: