简体   繁体   中英

Adding a Previous button in Javascript

I'm working on a adding a "previous" button to a fullscreen slider but I can't figure out how to make said button cycle back through all the slides so that when the user reaches the first slide if they click once again then it will go to the last slide.

If the user clicks the next button, it will loop from start to finish and back to start again, over and over, I just want the prev btn to do that but in reverse.

the codepen is http://codepen.io/heavymessing/pen/rxVOyN the javascript:

    var Boxlayout = (function() {

      var $el = $('#bl-main'),
        $sections = $el.children('section'),
        // works section
        $sectionWork = $('#bl-work-section'),
        // work items
        $workItems = $('#bl-work-items > li'),
        // work panels
        $workPanelsContainer = $('#bl-panel-work-items'),
        $workPanels = $workPanelsContainer.children('div'),
        totalWorkPanels = $workPanels.length,
        // navigating the work panels
        $nextWorkItem = $workPanelsContainer.find('nav > span.bl-next-work'),
        $prevWorkItem = $workPanelsContainer.find('nav > span.bl-prev-work'),
        // if currently navigating the work items
        isAnimating = false,
        // close work panel trigger
        $closeWorkItem = $workPanelsContainer.find('nav > span.close'),
        transEndEventNames = {
          'WebkitTransition': 'webkitTransitionEnd',
          'MozTransition': 'transitionend',
          'OTransition': 'oTransitionEnd',
          'msTransition': 'MSTransitionEnd',
          'transition': 'transitionend'
        },
        // transition end event name
        transEndEventName = transEndEventNames[Modernizr.prefixed('transition')],
        // support css transitions
        supportTransitions = Modernizr.csstransitions;

      function init() {
        initEvents();
      }

      function initEvents() {

        $sections.each(function() {

          var $section = $(this);

          // expand the clicked section and scale down the others
          $section.on('click', function() {

            if (!$section.data('open')) {
              $section.data('open', true).addClass('bl-expand bl-expand-top');
              $el.addClass('bl-expand-item');
            }

          }).find('span.close').on('click', function() {

            // close the expanded section and scale up the others
            $section.data('open', false).removeClass('bl-expand').on(transEndEventName, function(event) {
              if (!$(event.target).is('section')) return false;
              $(this).off(transEndEventName).removeClass('bl-expand-top');
            });

            if (!supportTransitions) {
              $section.removeClass('bl-expand-top');
            }

            $el.removeClass('bl-expand-item');

            return false;

          });

        });

        // clicking on a work item: the current section scales down and the respective work panel slides up
        $workItems.on('click', function(event) {

          // scale down main section
          $sectionWork.addClass('bl-scale-down');

          // show panel for this work item
          $workPanelsContainer.addClass('bl-panel-items-show');

          var $panel = $workPanelsContainer.find("[data-panel='" + $(this).data('panel') + "']");
          currentWorkPanel = $panel.index();
          $panel.addClass('bl-show-work');

          return false;

        });

        // navigating the work items: current work panel scales down and the next work panel slides up
        $nextWorkItem.on('click', function(event) {

          if (isAnimating) {
            return false;
          }
          isAnimating = true;

          var $currentPanel = $workPanels.eq(currentWorkPanel);
          currentWorkPanel = currentWorkPanel < totalWorkPanels - 1 ? currentWorkPanel + 1 : 0;
          var $nextPanel = $workPanels.eq(currentWorkPanel);

          $currentPanel.removeClass('bl-show-work').addClass('bl-hide-current-work').on(transEndEventName, function(event) {
            if (!$(event.target).is('div')) return false;
            $(this).off(transEndEventName).removeClass('bl-hide-current-work');
            isAnimating = false;
          });

          if (!supportTransitions) {
            $currentPanel.removeClass('bl-hide-current-work');
            isAnimating = false;
          }

          $nextPanel.addClass('bl-show-work');

          return false;

        });

        // navigating the work items: current work panel scales down and the previous work panel slides up
        $prevWorkItem.on('click', function(event) {

          if (isAnimating) {
            return false;
          }
          isAnimating = true;

          var $currentPanel = $workPanels.eq(currentWorkPanel);
          currentWorkPanel = currentWorkPanel > 0 ? currentWorkPanel - 1 : 8; // edit this number to your total number of panels -1
          var $prevPanel = $workPanels.eq(currentWorkPanel);

          $currentPanel.removeClass('bl-show-work').addClass('bl-hide-current-work').on(transEndEventName, function(event) {
            if (!$(event.target).is('div')) return false;
            $(this).off(transEndEventName).removeClass('bl-hide-current-work');
            isAnimating = false;
          });

          if (!supportTransitions) {
            $currentPanel.removeClass('bl-hide-current-work');
            isAnimating = false;
          }

          $prevPanel.addClass('bl-show-work');

          return false;

        });

        // clicking the work panels close button: the current work panel slides down and the section scales up again
        $closeWorkItem.on('click', function(event) {

          // scale up main section
          $sectionWork.removeClass('bl-scale-down');
          $workPanelsContainer.removeClass('bl-panel-items-show');
          $workPanels.eq(currentWorkPanel).removeClass('bl-show-work');

          return false;

        });

      }

      return {
        init: init
      };

    })();

the HTML:

      <body>
        <div class="container">
          <div id="bl-main">
            <section>

              <div class="bl-content">
                <h2>My Works</h2>
                <p>Mung bean maize dandelion sea lettuce catsear bunya nuts ricebean tatsoi caulie horseradish pea.</p>
                <ul id="bl-work-items">
                  <li data-panel="panel-1">
                    <a href="#"><img src="http://lorempixel.com/g/400/300/abstract/" /></a>
                  </li>
                  <li data-panel="panel-2">
                    <a href="#"><img src="http://lorempixel.com/400/300/" /></a>
                  </li>
                  <li data-panel="panel-3">
                    <a href="#"><img src="http://lorempixel.com/g/400/300/" /></a>
                  </li>
                  <li data-panel="panel-4">
                    <a href="#"><img src="http://lorempixel.com/400/300/sports/" /></a>
                  </li>
                </ul>
                <p>Illustrations by <a href="http://dribbble.com/isaac317/click">Isaac Montemayor</a></p>
              </div>
            </section>


            <!-- Panel items for the works -->
            <div class="bl-panel-items" id="bl-panel-work-items">
              <div data-panel="panel-1">
                <div>
                  <img src="http://lorempixel.com/g/400/300/abstract/" />
                  <h3>Fixie bespoke</h3>
                  <p>Iphone artisan direct trade ethical Austin. Fixie bespoke banh mi ugh, deep v vinyl hashtag. Tumblr gentrify keffiyeh pop-up iphone twee biodiesel. Occupy american apparel freegan cliche. Mustache trust fund 8-bit jean shorts mumblecore thundercats.
                    Pour-over small batch forage cray, banjo post-ironic flannel keffiyeh cred ethnic semiotics next level tousled fashion axe. Sustainable cardigan keytar fap bushwick bespoke.</p>
                </div>
              </div>
              <div data-panel="panel-2">
                <div>
                  <img src="http://lorempixel.com/400/300/" />
                  <h3>Chillwave mustache</h3>
                  <p>Squid vinyl scenester literally pug, hashtag tofu try-hard typewriter polaroid craft beer mlkshk cardigan photo booth PBR. Chillwave 90's gentrify american apparel carles disrupt. Pinterest semiotics single-origin coffee craft beer thundercats
                    irony, tumblr bushwick intelligentsia pickled. Narwhal mustache godard master cleanse street art, occupy ugh selfies put a bird on it cray salvia four loko gluten-free shoreditch.</p>
                </div>
              </div>
              <div data-panel="panel-3">
                <div>
                  <img src="http://lorempixel.com/g/400/300/" />
                  <h3>Austin hella</h3>
                  <p>Ethical cray wayfarers leggings vice, seitan banksy small batch ethnic master cleanse. Pug chillwave etsy, scenester meh occupy blue bottle tousled blog tonx pinterest selvage mixtape swag cosby sweater. Synth tousled direct trade, hella Austin
                    craft beer ugh chambray.</p>
                </div>
              </div>
              <div data-panel="panel-4">
                <div>
                  <img src="http://lorempixel.com/400/300/sports/" />
                  <h3>Brooklyn dreamcatcher</h3>
                  <p>Fashion axe 90's pug fap. Blog wayfarers brooklyn dreamcatcher, bicycle rights retro YOLO. Wes anderson lomo 90's food truck 3 wolf moon, twee jean shorts. Iphone small batch twee wolf yr before they sold out. Brooklyn echo park cred, portland
                    pug selvage flannel seitan tousled mcsweeney's.</p>
                </div>
              </div>
              <nav>
                <span class="bl-prev-work">&lt; Previous Project</span>
                <span class="bl-next-work">Next Project &gt;</span>
                <span class="close fa fa-close"></span>
              </nav>
            </div>

          </div>
        </div>
        <!-- /container -->
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <script src="js/boxlayout.js"></script>
        <script>
          $(function() {
                  Boxlayout.init();
                });
        </script>
        <script src="http://tympanus.net/codrops/adpacks/csscustom.js"></script>
        <script src="http://tympanus.net/codrops/wp-content/plugins/oiopub-direct/js.php?type=banner&align=center&zone=1"></script>
      </body>

      </html>

Thanks

You should notice this string: currentWorkPanel = currentWorkPanel > 0 ? currentWorkPanel - 1 : 8; // edit this number to your total number of panels -1 currentWorkPanel = currentWorkPanel > 0 ? currentWorkPanel - 1 : 8; // edit this number to your total number of panels -1

As comment says, you should change 8 to 4 (number of your items) - 1 = 3

So finally, you should get this:

currentWorkPanel = currentWorkPanel > 0 ? currentWorkPanel - 1 : 3;

UPDATE:

Cleaner solution whould be to calculate final number depending on your total items count using variable totalWorkPanels :

currentWorkPanel = currentWorkPanel > 0 ? currentWorkPanel - 1 : totalWorkPanels-1;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM