Lets say I have a jquery plugin called widget which can be used on multiple elements
e.g. $('.myClass').widget();
After the page has loaded I am dynamically adding HTML which contains more elements that have the class myClass. If I run the code above again, the previously loaded widgets will get initialized again.
One solution I came up with is to remove the class myClass after the widget is initialized.
Another idea is to use .data() and store an init flag check if it exists when the plugin loads.
Is there a better way of doing this?
$(".myClass-init").widget().removeClass(".myClass-init")Add a new class called
myClass-initThis means you can continue using
myClassfor CSS styling and are using a separate new class merely for functionality.You could use
data-attributes but the selectors for those are slower. That’s a question of whether you thinkdata-attributes are more semantic then an extraclass