Bind custom event to dynamic created elements

I’ve been binding events to dynamically created elements without any kind of issues by using:

$(document).on(event, element, function)

Now I want to bind a custom event and I just canĀ“t get it to work.

The event is a JS plugin to handle single e double click. If I use it like this:

$('#test').oneordoubleclick({
    oneclick: function () {
        alert('you have clicked this node.');
    },
    dblclick: function () {
        alert('you have double clicked this node.');
    }
});

It works like a charm, but, as I transform the code to bind the event to dynamically created elements, like this:

$(document).on('oneordoubleclick', '#test', {
    oneclick: function () {
        alert('you have clicked this node.');
    },
    dblclick: function () {
        alert('you have double clicked this node.');
    }
});

It stops working!

It wasn’t supposed to work? What am i doing wrong? It is possible to do what i want to accomplish?

1 thought on “Bind custom event to dynamic created elements”

  1. According to my understanding, .oneordoubleclick is not an Event, just like .footable or .tooltip. Therefore, you cannot put it in $(document).on("oneordoubleclick","#test", ...)

    Here’s my solution, with the aid of the plugin source code:

    // Custom functions
    let singleClick = function () { // your function when is single click
        alert('you have clicked this node.');
    }
    
    let doubleClick = function () { // your function when is double click
        alert('you have double clicked this node.');
    }
    
    // Necessary to differentiate is single or double click
    let timer,
        do_click = function (e, fx) {
            clearTimeout(timer);
            timer = setTimeout(function () {
                fx();
            }, 400); // if there is no another click between 0.4s, then it is single click
        },
        do_dblclick = function (e, fx) {
            clearTimeout(timer); // the single click function will not be called
            fx();
        };
    
    // Listener
    $(document) .on("click",    "#test", function (e) { do_click(e, singleClick) })
                .on("dblclick", "#test", function (e) { do_dblclick(e, doubleClick) })
    

    Correct me if I’m wrong.

    Reply

Leave a Comment