Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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");

Doing that, this element will display a tooltip with "Create appointment" text.

Like this I have any others.

The problem begin when I insert some elements via JS in my DOM.

There is any way to delegate this operation to avoid calling this every time I insert one element?

Update

I'm looking for a simple solution to setup my tooltips. The DOMObserver looks too heavy for use here. Or not?

like image 476
Beetlejuice Avatar asked Apr 17 '26 01:04

Beetlejuice


1 Answers

A mutation observer seems appropriate, 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");
        }
    } );
}
like image 113
Scott 'scm6079' Avatar answered Apr 18 '26 14:04

Scott 'scm6079'



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!