I want to know, if it's possible, how to check in javascript if an element has changed or an attribute of it?
I mean something like window.onhashchange
for an element something like:
document.getElementById("element").onElementChange = function();
As I know onchange
is something like this, but will it work if I want to know in this way:
var element = {};
element.attribute = result;
element.attribute.onchange = function();
I believe there is no such event. However, you can use setInterval or setTimeout to watch for element changes and use it to react accordingly.
You might consider a mutation observer.
to do this you first create a callback (fired when the dom element changes)
assign it to an observer
var observer = new MutationObserver(callback);
Then tell the observer what to watch
observer.observe('<div></div>', observerOptions);
From: Mozilla page on Mutation Observers
As far as I understand you want onChange on javascript object Properties. The answer is no, it doesn't exist as far as I know.
But you can make a setter function like this (As a proof of concept):
now you get an alert box with 'something changed from undefined to Hello World!'. And
(element.something === 'Hello World!')
will returntrue
.if you now call:
you get an alert box with 'something changed from Hello World! to Goodbye World!'.
Off course you have to set the property only via the
setProperty
method in all of your code if you want to capture this event!Edit:
At some time in the future, you might be able to use Object.observe().
Edit 2:
Now there's also proxies.
I guess you'd need a way to capture the event which triggered the change in attribute rather than the change in attribute. The change in attribute could only either be due to your CSS or your javascript, both being manifestations of the user's actions.
I did this. It works pretty well. I would have used the setProperty method if I had known.