David G
David G

Reputation: 96810

Why doesn't this onchange event work?

if (!localStorage.text) localStorage.text = document.body.innerHTML;

function ifChanged() {
    document.body.innerHTML.onchange = function() {
        if (document.body.innerHTML !== (localStorage.text)) alert("No match");
    };
}

ifChanged();

It doesn't check if it changed. What went wrong?

Upvotes: 2

Views: 3379

Answers (2)

Saxoier
Saxoier

Reputation: 1287

document.body.innerHTML returns a string and String.onChange and String.setEventListener('change', ...); are undefined. The DOM 2 introduce MutationEvents which will fire when the DOM is changed. Unfortunately, those events are not widely implemented and may slow down every change in the DOM.

Upvotes: 4

Cameron
Cameron

Reputation: 98776

It's not working because the onchange event is for form fields (it fires when the field's value changes). It is not fired when the HTML changes, just, for example, when a user types a key in a textbox.

The best way to know when something on the page changes is to have the code that is making the changes in the first place signal that a change is being made (this could be cleanly done with some sort of event broadcast).

If you really want to do it this way, you could use a timer that periodically polls for changes:

setInterval(ifChanged, 1000);    // Check once every second (1000ms)

Upvotes: 4

Related Questions