Search code examples
javascriptdomeventslistenerdom-events

DOM Listener on Static Table Change


I'm trying to add listener to my table in order to call another jJavascript function.

My app is a simple upload script, when user chooses a file it uploads and creates new row in the table. Therefore at each creation of new row I would like to call a Javascript function.

My sample code is the following:

$("#fayls").bind("DOMNodeInserted", function() {
    $(".chzn-select").chosen();
    alert('ha cambiato')
});

Where fayls is the id of my table.

When I run this code, it calls this event infinitely instead of just one.

How should I solve this problem ?

Thanks.


Solution

  • As you all mentioned, the problem is caused from chosen, for each drop box item in chosen, it fires the DOM event, therefore I'll have infinite loop.

    I found a simple solution by just filtering the unnecessary events:

     $("#listenMe").bind("DOMNodeInserted", function(event) {
    
            var targetName =  event.target.nodeName.toString() ;
            if (targetName == "TR") {
                $(".chzn-select").chosen();
                //alert('ha cambiato - Event Node Name:' + event.target.nodeName)
            }
        });
    

    Therefore it only runs when a new row added into a table