click event fires multiple times issue, how to?

Patrioticcow picture Patrioticcow · Dec 22, 2013 · Viewed 7.2k times · Source

I have a button. when I click it I am appending some buttons to the DOM.

The issue I have is that those buttons that I am appending fire multiple times.

$(el).on('click', function (e) {
    key();
});

function key() {
    $(document).on('click', '#key li', function () {
        console.log($(this));
    });
}

First time key() is called, the console.log fires once

The second time I call key() the console.log fires twice

And so on

I've tried adding $(document).find('#key li').unbind('click'), but that doesn't seem to work

Any ideas?

edit:

Here is an jsfiddle example (shown below).

To reproduce, click on the test button, then on the click,then one 1 2 3 and repeat the process

You will notice that the second time you go through the process the text doubles

Answer

Harsha Venkatram picture Harsha Venkatram · Dec 22, 2013

Do this

function key() {
    $('#key li').unbind('click');
    $('#key li').bind('click', function () {
        console.log($(this));
    });
}

or you could do

function key() {
    $('#key').find('li').unbind('click');
    $('#key').find('li').bind('click', function () {
        console.log($(this));
    });
}

I guess the second one will surely work.

Updated method

function key() {
    $(document).off('click', '#but_placeholder button');
    $(document).on('click', '#but_placeholder button', function () {
        $('input').val($('input').val() + $(this).html());
    });
}