JQuery delegate attribute changes
In my page, I change one attribute of an element based on another attribute. Like this:
$("body").find("[data-action=new]").attr("data-original-title", "Create appointment");
This element will then display a tooltip with the text "Create an appointment".
I have others.
The problem starts when I insert some elements via JS into my DOM.
Is there a way to delegate this operation to avoid calling this every time I insert one item?
Update
I am looking for a simple solution for customizing tooltips. DOMObserver looks too heavy to use here. Or not?
+3
source to share
1 answer
The mutation watcher seems to be appropriate by monitoring the addedNodes property:
var targetNodes = $("body"); // best to make this more specific, e.g. .myNodes
var MutationObserver = window.MutationObserver || window.WebKitMutationObserver;
var myObserver = new MutationObserver (mutationHandler);
var obsConfig = { childList: true, characterData: true, attributes: true, subtree: true };
targetNodes.each ( function () {
myObserver.observe (this, obsConfig);
} );
function mutationHandler (mutationRecords) {
mutationRecords.forEach ( function (mutation) {
if (typeof mutation.addedNodes == "object") {
var jq = $(mutation.addedNodes);
jq.find("[data-action=new]").attr("data-original-title", "Create appointment");
}
} );
}
+1
source to share