Keith
Keith

Reputation: 4137

jquery onclick from div to div

I had this problem here javascript - Need onclick to go full distance before click works again that I couldn't seem to figure out how to make it work. So I am going on to plan B which is to try to go from div to div within a scroll. Currently, my HTML looks something like this:

HTML

<div class="outerwrapper">
    <div class="innerwrapper">
        <div class="holder"></div>
        <div class="holder"></div>
        <div class="holder"></div>
        <div class="holder"></div>
        <div class="holder"></div>
        <div class="holder"></div>
    </div>
</div>
<div class="buttons">
    <div id="left">
    <div id="right">
</div>

Javscript

$(function () {  // DOM READY shorthand

    $("#right, #left").click(function () {
        var dir = this.id == "right" ? '+=' : '-=';
        $(".outerwrapper").stop().animate({ scrollLeft: dir + '251' }, 1000);
    });

});

So currently I was trying to get it to move the full 251px first before another click event could fire. The problem is when a user clicks on the arrow multiple times, it resets the event and starts over from within the scroll so instead of going from frame to frame, it could start in the middle of the frame and end in the middle of the frame. Since I haven't been able to figure out how to make the javascript complete its action first so it goes the full 261 px before the event can happen again, I was wondering is there a way to transition from div to div so the user can click as many times as they like and it will transition smoothly from div to div and not end up in the middle once its done?

Upvotes: 1

Views: 145

Answers (1)

adeneo
adeneo

Reputation: 318352

That's what on() and off() are for :

$(function () {
    var buttons = $("#right, #left");
    buttons.on('click', ani);

    function ani()
        buttons.off('click');

        var dir = this.id == "right" ? '+=' : '-=';
        $(".outerwrapper").animate({ scrollLeft: dir + '251' }, 1000, function() {
            buttons.on('click', ani);
        });
    }
});

Another option would be to not rely on the currently scrolled position, but a variable you keep track of yourself.

$(function () {
    $("#right, #left").on('click', function() {
        var wrap = $(".outerwrapper"),
            dir  = this.id == "right" ? 251 : -251,
            Left = (wrap.data('scroller') || 0)  + (dir);

        $(".outerwrapper").animate({ scrollLeft: Left }, 1000);
        wrap.data('scroller', Left);
    });
});

Upvotes: 3

Related Questions