aslum
aslum

Reputation: 12274

combining Hover with an If statement in jQuery

I'm using the Cycle plugin for a slideshow. It's got a built-in "Pause on mouse over" feature, however I want to make the navigation elements change on mouse over as well.

This is easily enough accomplished, but I'd like to maintain the pause/play state. That is, if the user has clicked the pause button I want to do nothing when they mouse over. However if they haven't paused it, I'd like to do something on hover and unhover.

Here's the code for when the click the pause/play button:

$('#pauseButton').click(function() {
    $('#news').cycle('pause');
    $('#pauseButton').hide();
    $('#playButton').show();
});
$('#playButton').click(function() {
    $('#news').cycle('resume');
    $('#pauseButton').show();
    $('#playButton').hide();
});

My first attempt to accomplish this is such:

$('#news div').hover(function() {
    $('#pauseButton').show();
    $('#playButton').hide();    
    $('#paused').css({background:"#ff9000"});
}, function(){
    $('#pauseButton').hide();
    $('#playButton').show();
});

The problem is that regardless of whether the user had paused the slide show, mousing-over and then off would unpause the slideshow.

It seems like it should be easy to put an "if" statement in there somewhere but I can't figure out where it would go exactly.

Upvotes: 1

Views: 1235

Answers (1)

Jasper
Jasper

Reputation: 76003

If you disable the plugin's "pause-on-mouseover" option then you can do it yourself:

//setup a flag to detect if the show should play or not
var pause_show = false;

//pause on mouseover 
$('#slideshow-id').on('mouseover', function () {

    $('#news').cycle('pause');
    $('#pauseButton').hide();
    $('#playButton').show();

//play on mouseleave only if flag is not set to `false` (meaning the pause button has not been clicked)
}).on('mouseleave', function () {

    //if the show has not been paused with the pause button then resume the show
    if (pause_show === false) {
        $('#news').cycle('resume');
        $('#pauseButton').show();
        $('#playButton').hide();
    }
});

//set flag to true (block play on mouseleave) when the user clicks on the 
$('#pauseButton').on('click', function () {
    pause_show = true;
});
$('#playButton').on('click', function () {
    pause_show = false;
});

Note that .on() is new in jQuery 1.7 and is the same as .bind() in this case.

Upvotes: 1

Related Questions