I have a page that has rows, each of which includes few input fields and a button that does something. Button has class .super-button. Let’s say I have 23 rows, and I’ve just retrieved 24th over AJAX and inserted it bellow, and I want to bind some functionality to it’s button on click event.
What I’m doing right now is:
$(".super-button").off("click");
$(".super-button").on("click", function(){
/// Do some awesome functionality
});
Is there a better way to bind event to newly inserted element in DOM?
You can delegate the events to the immediate parent that is static.
By doing so you can associate an event just once..
This will make sure you do not need to use .on() and .off() every single time a new element is created.
NOTE : Here body can be replaced by the closest static parent , maybe a table in which the rows are present.. I am delegating it using body as I do not know the ,markup.