basilio / responsiveCarousel

Simple carousel
MIT License
113 stars 64 forks source link

Dynamic insert of items, bind multiple times the prev/next listeners #47

Open gfot opened 7 years ago

gfot commented 7 years ago

Hi, I have a snippet that demonstrates the following:

If you want to add dynamically, either by using AJAX or a click event handler that adds new items to carousel, you have to initialize the carousel after each insertion. Then the click listeners of the prev/next navigation button are bind many times and thus on click the event is triggered multiple times.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>responsiveCarousel demo</title>
  <link rel="stylesheet" href="./style.css">
</head>
<body>

  <div class="example">
    <h3>Text Content</h3>

    <div>
      <a href="#" class="add-text">ADD</a>
    </div>

    <div id="nav-05" class="crsl-nav">
      <a href="#" class="previous">« Previous</a>
      <a href="#" class="next">Next »</a>
    </div>

    <div class="gallery gallery-05 crsl-items" data-navigation="nav-05">
      <div class="crsl-wrap">
        <section class="crsl-item">
          <h2>Demo header 1</h2>
          <blockquote><p>Demo quote text 1</p></blockquote>
          <p>Demo text 1</p>
        </section>
      </div>
    </div>
  </div>

  <script src="./jquery-2.1.4.js"></script>
  <script src="./responsiveCarousel.js"></script>
  <script>
    function getNewLine(num) {
      return '<section class="crsl-item">'
          + '<h2>Demo header ' + num + '</h2>'
          + '<blockquote>'
          + '<p>Demo quote text ' + num + '</p>'
          + '</blockquote>'
          + '<p>Demo text ' + num + '</p>'
          + '</section>'
    }

    $(document).ready(function(){
      console.log('strt');
      $('.crsl-items').carousel({ visible: 3, itemMinWidth: 300, itemMargin: 20 });

      $('.add-text').on('click', function(event) {
        console.log('Adding new text');

        var size = $('section').length;
        var $newLine = $(getNewLine(size + 1));

        var $crslWrapper = $('.crsl-wrap');
        $crslWrapper.append($newLine);

        $('.crsl-items').carousel({ visible: 3, itemMinWidth: 300, itemMargin: 20 });
      });
    });
  </script>
</body>
</html>

Maybe I miss something but shouldn't the new carousel initialization discard any previous listeners? Is there another way to do this?