Change javascript event

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Change javascript event

Post 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]
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
josh
DevNet Master
Posts: 4872
Joined: Wed Feb 11, 2004 3:23 pm
Location: Palm beach, Florida

Post 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
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post 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..
Post Reply