Page 1 of 1

Change javascript event

Posted: Fri Dec 23, 2005 10:45 am
by pickle
Hi everyone,

I'm wondering how to change what function is called when an onClick event is fired. I've got a link that, when clicked, calls displayChildren(). I want displayChildren to change what function is called when the link is clicked again, to hideChildren().

I've tried:

Code: Select all

document.getElementById(p_id).childNodes[0].onclick = 'function onclick(event){hide_children("' + p_id + '");}';
and

Code: Select all

document.getElementById(p_id).childNodes[0].onclick = 'hide_children();';
to no avail.

Any ideas?

[Update: I've changed my approach to create a function toggleChildrenDisplay and make that function determine what to do. I still haven't found any way to update the onClick event. If you know how to do it though, leave your solution for posterity - others might still benefit]

Posted: Sun Dec 25, 2005 12:48 am
by josh
Well I usually use a "toggle" approach but often if the functions are not inverses of eachother (one reverses the acts of the other) I would have "proxy function"

Code: Select all

var state;
function clickhandler(ofwhat) {
if (state[ofwhat] == 1) {
// do this function
} else if (state[ofwhat]==2) {
//do that function
} else {
//do something else
}
}
then in your onlick event

Code: Select all

onclick="clickhandler('mylink')"

if you see where I'm going with this, the clickhandler function looks at the "state" array to decide which function to call for each clickable item in your page, changing the onlick function is as easy as changing that objects value in the "state" array

Posted: Sun Dec 25, 2005 7:44 am
by feyd
javascript, somewhat like php, but more like C, has function pointers.

For a given function called "hide_children," you may replace the event with its function pointer:

Code: Select all

document.getElementById(p_id).childNodes[0].onclick = hide_children;
However, you may with to append to the event's coding, in which case, using addevent (or whatever the name is) should work better..