onChange event when div content changed

11,992 views
Skip to first unread message

Hipnotik

unread,
Sep 2, 2009, 10:07:58 AM9/2/09
to Prototype & script.aculo.us
Hi
How to call some action if content of the div element has changed?

I'm talking about something like this:
$("my-div").observe("change", function(e) {
alert("hello");
});

Expecting behavior:
I have this
<div id="my-div">some text</div>

now I'm changing "some text" to "some other text" and "alert("hello")"
should be fired.

Thnaks for help.

Walter Lee Davis

unread,
Sep 2, 2009, 11:30:09 AM9/2/09
to prototype-s...@googlegroups.com
There's no reliable cross-browser event that gets fired when the
content of a DIV (as opposed to a form element, say) changes. One
thing you might try would be to have a PeriodicalExecuter running.
Have it compare a global variable with the current innerHTML of that
DIV, and if they don't match, fire the event and update the global
variable. This may be more difficult than I am saying it here, it's
often quite hard to get a PE to gather an external variable value more
than once (at the moment the PE function is instantiated).

Walter

Hipnotik

unread,
Sep 2, 2009, 1:30:18 PM9/2/09
to Prototype & script.aculo.us
Thanks Walter!
I would like to avoid of using PE and global variable to store current
innerHTML. I thought that it will be quiet easy and any trick can help
me...
There is other way - hidden form field and prototype's observer. But
this solution doesn't satisfy me too.

Anyway, thanks.

RobG

unread,
Sep 3, 2009, 8:54:44 AM9/3/09
to Prototype & script.aculo.us
There is no change event specified for div elements, what you are
looking for is provided by DOM mutation events:

<URL: http://www.w3.org/TR/DOM-Level-2-Events/events.html#Events-MutationEvent
>

OK in Firefox, Opera, Safari and a few others, but not IE.

Some help here:

<URL: http://www.howtocreate.co.uk/tutorials/javascript/domevents >

The best cross-browser strategy is to get the function that modifies
the DOM to call the function you'd like to add as a DOMSubtreeModified
listener.


--
Rob

Marko Zabcic

unread,
Sep 3, 2009, 9:11:48 AM9/3/09
to Prototype & script.aculo.us
You could use prototype custom events. See example here:
http://jsbin.com/ayiku

But you will have to fire function manually after update or override
default Element.update function to do it for you.

Marko

Hipnotik

unread,
Sep 3, 2009, 5:33:59 PM9/3/09
to Prototype & script.aculo.us
@RobG
I'm not sure that DOMSubtreeModified works in the IE. I tried to use
it and I think it doesn't.

@Marko
That's the problem... I don't want to fire it manually.

But thanks guys for help.

Marko Zabcic

unread,
Sep 4, 2009, 6:52:02 AM9/4/09
to Prototype & script.aculo.us
If you override Element.update function it's almost automagically :-)
http://jsbin.com/utuvu

I can't get closer to the solution than this :-)

Marko
Reply all
Reply to author
Forward
0 new messages