Search code examples
javascriptjqueryhandlerjquery-events

How do I use a function with parameters as a handler when using on() in jQuery?


$('#editor'+id).on("click dbclick mousedown mousemove mouseover mouseout mouseup keydown keypress keyup blur change focus select", {param1:id}, editor_change);

function editor_change(id){
...does stuff...;
}

This function is supposed to take each textarea element with the id "editor" + a unique id (e.g. "editor24") and add a handler that detects an edit in the textarea. The function it is calling editor_change takes one parameter "id" that I need to include in the handler. How do I include this parameter when creating the handler?


Solution

  • As there actually is a built in method to pass data in exactly that way, I'll post it as answer, as I assume that is what you're looking for, not how to extract a number from an elements ID :

    $('#editor'+id).on("click ...more events", {param1:id}, editor_change);
    
    function editor_change(event){
        var passed_id = event.data.param1;
        alert(passed_id);
    }
    

    As you see, the passed object is available as event.data, and that's how the data parameter works in jQuery.

    FIDDLE