I currently have the following code:
$('#loginLink, #registerLink').click(function () {
dialog(this);
return false;
});
$('#detailData')
.on('click', '.modalDeleteLink, .modalEditLink', function () {
dialog(this);
return false;
})
There are just one of #loginLink and #registerLink but there could be up to a hundred elements with the classes .modalDeleteLink and .modalEditLink.
I was thinking to change all of these elements so they have a class of .dialogLink and then just using the following code:
$("body").on("click", ".dialogLink", function(){
dialog(this);
return false;
});
This code is a lot easier to maintain. However would there be any performance disadvantage in attaching this to the body?
You don’t need to worry about performance, unless you have hundreds of handlers or extremely large document.
Extract from documentation:
In most cases, an event such as click occurs infrequently and performance is not a significant concern. However, high frequency events such as mousemove or scroll can fire dozens of times per second, and in those cases it becomes more important to use events judiciously. Performance can be increased by reducing the amount of work done in the handler itself, caching information needed by the handler rather than recalculating it, or by rate-limiting the number of actual page updates using setTimeout.
Attaching many delegated event handlers near the top of the document tree can degrade performance. Each time the event occurs, jQuery must compare all selectors of all attached events of that type to every element in the path from the event target up to the top of the document. For best performance, attach delegated events at a document location as close as possible to the target elements. Avoid excessive use of document or document.body for delegated events on large documents.