Search code examples
jqueryclickpnotify

jQuery PNotify button click fired multiple times


I have a number of images. Clicking on any of them opens a PNotify pop-up.

The PNotify pop-up has a simple form with a text field and a Save button. On clicking the button, it simply adds a paragraph of text to the clicked image.

But when I press the Save button, it appends the text multiple times and it appends +1 with every following click, e.g. first 1, then 2, then 4, then 6 etc.

$('#pic_wrapper').on('click', '.mark', function(e) {
    var notice = new PNotify({
      ...
    });

    $('#text_form button[name=save]').on('click', function() {
      $('#' + e.target.id).append('<p class="text">' + $.trim(
        $('#input_text').val()) + '</p>');
      notice.remove();
    });
  });

The click seems to be firing multiple times. How can I stop that and only have it fired once per click?


Solution

  • Event handler is attach multipal time so you face the problem .The .off() method removes event handlers that were attached with .on().

    $('#text_form button[name=save]').off().on('click', function() {
      $('#' + e.target.id).append('<p class="text">' + $.trim($(
        '#input_text').val()) + '</p>');
      notice.remove();
    });