...

View Full Version : Attaching Custom Methods to JavaScript Elements



SyQo
12-17-2006, 03:16 AM
The JavaScript Array Object has the built-in reverse() method, which can be implemented like so:

ARRAY_NAME.reverse()
Simple enough, right? Well, I'm bewildered as to how to do this with my own methods. For example, let's assume I've got a function called changeColor, and I wanted to attach it to an element like so:


document.getElementById('someElement').changeColor('red');

How would I go about doing that?

whizard
12-17-2006, 03:32 AM
I think what you're talking about are event handlers.. I'm not exactly a JS whiz, but hopefully this link will help, if not, my bad!

http://developer.mozilla.org/en/docs/DOM:element.addEventListener

Dan

SyQo
12-17-2006, 03:37 AM
Sorry, way off. I'm almost certain it can be done (attaching functions, that is) using JavaScript Objects, I just can't seem to piece it together. It could just as easily be done with this function:


function changeColor(element, color)
{
element.style.color = color;
}

but I'm a stickler for knowing how to do things, and I've always pondered the possibility of attaching functions. There are several native functions that act via attachment (the ARRAY.reverse() that I mentioned previously is a perfect example), so it must be possible.

koyama
12-17-2006, 03:42 AM
... or do you mean assigning your own methods? Perhaps this example will help you.

<html>
<head>
<title>test</title>
<script type="text/javascript">
function setColor(myColor) {
this.style.color = myColor;
}
</script>
</head>
<body>
<span id="monkey">hello</span>
<input type="button" value="go" onclick="document.getElementById('monkey').changeColor('red')" />

<script type="text/javascript">
document.getElementById('monkey').changeColor = setColor;
</script>

</body>
</html>

SyQo
12-17-2006, 03:48 AM
So very close. In order for that approach to work, however, I'd have to do


document.getElementById('ELEMENT_IN_QUESTION').changeColor = setColor;

for every single element I'd like it to work with, though. Not exactly efficient. Is this the only way to do it, though?

jkd
12-17-2006, 03:50 AM
So very close. In order for that approach to work, however, I'd have to do


document.getElementById('ELEMENT_IN_QUESTION').changeColor = setColor;

for every single element I'd like it to work with, though. Not exactly efficient. Is this the only way to do it, though?



HTMLElement.prototype.changeColor = setColor;


In Firefox and Opera, at least.

SyQo
12-17-2006, 03:55 AM
Works to perfection. Much thanks to both of you.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum