Anthony
Anthony

Reputation: 979

Javascript event triggering creating multiple button .on('click)

I'm using HTML slim for the code below.

.page
  .paper
    button.button.js-copier I copy things

- content_for :js_includes do
  javascript:
    var startingHtml = $('.page').html();

    function initializePlugin() {
      $('.js-copier').each(function () {
        $(this).on('click', function () {
          $('.page').append(startingHtml);
          $(document).trigger('page-refreshed');
        });
      });
    }

    // Run it right away
    initializePlugin();

    $(document).on('page-refreshed', initializePlugin);

Is there a way to fix the fact that when I click on the "I copy things" button, it creates multiple copies of the button as it is iterating over all the button from the button that was selected?

Also, is there a better way to write this code. All I'm trying to do is duplicate the button anytime I click on any buttons(first and any new button created buttons)

-Anthony

Upvotes: 0

Views: 230

Answers (1)

rafaelcastrocouto
rafaelcastrocouto

Reputation: 12161

First change this:

  $('.js-copier').each(function () {
    $(this).on('click', function () {
      ...

to this:

  $('.page').on('click', '.js-copier', function () {
    ...

Read this to understand https://learn.jquery.com/events/event-delegation/#event-propagation

Then remove the 'page-refreshed' event because you don't need it:

   $(document).trigger('page-refreshed');
   ...
   $(document).on('page-refreshed', initializePlugin);

Demo solution:

var startingHtml = $('.page').html();

function initializePlugin() {
  $('.page').on('click', '.js-copier', function () {
    $('.page').append(startingHtml);
  });
}

// Run it right away
initializePlugin();
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="page">
  <div class="paper">
    <button class="button js-copier"> I copy things</button>
  </div>
</div>

Upvotes: 2

Related Questions