Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
gfot opened this issue Mar 7, 2017 · 0 comments
Open

Comments

@gfot
Copy link

gfot commented Mar 7, 2017

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant