Tuesday, September 6, 2016

bind javascript event for future element without attaching any event - DOMNodeInserted (alternative of .on )

1st approach what we did always 

$('body').on('click','.abcd',function () {
        $(this).prev('.teaseRestText').toggle();
        if ($(this).attr('toggle') == '0') {
            $(this).html('Show Less...').attr('toggle', 1);
        }
        else {
            $(this).html('Show More...').attr('toggle', 0);
        }
});


But sometimes, situation came that we don't have any event like "click " but still need a function to execute for dynamic elements. 

I came to this solution  



$(document).bind('DOMNodeInserted', function(event) {
    $('#table tr').each(function (e) {
        console.log(e);
    });
});


No comments:

Post a Comment