mix
mix

Reputation: 7151

Why does waitForKeyElements() only trigger once despite later changes?

For several years I've used the waitForKeyElements() function to track changes in webpages from a userscript. However, sometimes I've found it doesn't trigger as expected and have worked around out. I've run into another example of this problem, and so am now trying to figure out what the problem is. The following is the barest example I can create.

Given a simple HTML page that looks like this:

<span class="e1">blah</span>

And some Javascript:

// function defined here https://gist.github.com/BrockA/2625891
waitForKeyElements('.e1', handle_e1, false);

function handle_e1(node) {
    console.log(node.text());
    alert(node.text());
}

setInterval(function() {
    $('.e1').text("updated: "+Math.random());
}, 5000);

I would expect this code to trigger an alert() and a console.log() every 5 seconds. However, it only triggers once. Any ideas?

Here's a codepen that demonstrates this.

Upvotes: 2

Views: 1437

Answers (1)

Brock Adams
Brock Adams

Reputation: 93493

By design and default, waitForKeyElements processes a node just once. To tell it to keep checking, return true from the callback function.
You'll also want to compare the string (or whatever) to see if it has changed.

So, in this case, handle_e1() would be something like:

function handle_e1 (jNode) {
    var newTxt  = jNode.text ();
    if (typeof this.lastTxt === "undefined"  ||  this.lastTxt !== newTxt) {
        console.log (newTxt);
        this.lastTxt = newTxt;
    }
    return true;    // Allow repeat firings for this node.
}


With the constant string comparisons though, performance might be an issue if you have a lot of this on one page. In that scenario, switching to a MutationObserver approach might be best.

Upvotes: 2

Related Questions