Javier Villanueva
Javier Villanueva

Reputation: 4068

Function firing twice when bound to before callback using jQuery cycle plugin

I'm using the jQuery Background Position plugin and the jQuery Cycle plugin to try to make a slider and a background image animate at the same time the slides are scrolling. Here's a sample of what I have so far:

HTML

<div class="container">
    <div class="slider">
        <div class="pane">
            Text asd dddsa sadsad
        </div>
        <div class="pane">
            Text asd dddsa sadsad
        </div> 
        <div class="pane">
            Text asd dddsa sadsad
        </div>        
    </div>
    <a href="#" id="prev-slide">&lt; Prev</a>
    <a href="#" id="next-slide">Next &gt;</a>
</div>​

JS

$(function() {
    // Animate background when clicking slider arrows
    $('#prev-slide').on('click', function(event) {
        event.preventDefault();
        slideBgForward();
    });

    $('#next-slide').on('click', function(event) {
        event.preventDefault();
        slideBgBackward();
    });

    $('.slider').cycle({
        fx   : 'scrollHorz',
        next : '#next-slide',
        prev : '#prev-slide',
        before : function(currSlideElement, nextSlideElement, options, forwardFlag) {
            if (forwardFlag) {
                slideBgBackward();
            } else {
                slideBgForward();
            }                
        }            
    });

    // Slide background forwards
    function slideBgForward() {
        $('.container').animate({
            backgroundPosition: '-=20% 0'
        }, 1500);
    }

    // Slide background backwards
    function slideBgBackward() {
        $('.container').animate({
            backgroundPosition: '-=20% 0'
        }, 1500);
    }
});​

http://jsfiddle.net/vengiss/gshtZ/

If I leave the slider scroll by itself it works as intended, however if I click the next/prev links to move trough the slides the background animates twice, I believe it's because the slide functions are being called when the links is clicked AND before the slide starts scrolling. Is there a way to make it just scroll once?

Thanks in advance.

Upvotes: 0

Views: 940

Answers (1)

floatingLomas
floatingLomas

Reputation: 8747

I think your problem is that you have asked ('.slider').cycle() to handle your next and prev, AND you are also asking jQuery to handle them too - and each is doing what you ask, and as such, your background is animating twice.

I would be tempted to try removing / disabling $('#next-slide').on('click') and $('#prev-slide').on('click') and see what happens.

Upvotes: 2

Related Questions