How do I jump to a specific slide upon clicking a button using jQuery?

- 1 answer

Ad

I am using adopted code that uses switches and hashes to navigate between divs on a website, showing only one at a time, like a slideshow. Here's what it looks like:

        $("#forward-button").click(function() {
            var h = window.location.hash;
            var s = h.replace("#","");
            var n = parseInt(s) + 1 + '';
            if( s == 20 ) { } else {
            $( "#slide-" + s ).toggle( "drop", { direction: "left" }, 400 );
            $( "#slide-" + s ).promise().done(function(){
            $( "#slide-" + n ).toggle( "drop", { direction: "right" }, 400 ); });
            rewriteSlideLabel(n);
            window.location.hash = "#" + n;
            }
        });

This is working great, but I would like the added functionality of having buttons that can jump to specific slides instantly (rather than having to go through one by one to get to where you want).

I placed some buttons on the side to accomplish this, but I can't figure out the actual code. I've tried things like:

 $("#button2").click(function() {
        jumpToHash("2");rewriteSlideLabel("2");
 });

but that doesn't have the fancy animation that makes navigating between slides look professional.

Please help. Thank you!

http://codepen.io/anon/pen/qbNOYG

Ad

Answer

Ad

fiddling around with your code, I made a new function for you to use:

  var jumpToSlide = function(number) {
            var h = window.location.hash;
            var s = h.replace("#","");
            var n = number;
            if( s == 20 ) { } else {
            $( "#slide-" + s ).toggle( "drop", { direction: "left" }, 400 );
            $( "#slide-" + s ).promise().done(function(){
                $( "#slide-" + n ).toggle( "drop", { direction: "right" }, 400 ); });
                rewriteSlideLabel(n);
                window.location.hash = "#" + n;
            }
   }

then from there, you can just call the following:

 $("#button1").click(function() {
        jumpToSlide(1);
 });

I hope this helps!

Ad
source: stackoverflow.com
Ad