assigning stuff to onclick, via javascript

Y

yawnmoth

Say I wanted to assign something to this.onclick. I could do this by
doing "this.onclick = Function('...')", but I'm not sure if that's the
prefered way to do it, per the official W3C specs?
 
M

Martin Honnen

yawnmoth said:
Say I wanted to assign something to this.onclick. I could do this by
doing "this.onclick = Function('...')", but I'm not sure if that's the
prefered way to do it, per the official W3C specs?

Is there any official W3C spec that defines an onclick property on HTML
or XML element nodes? I don't think so.
The HTML 4 specification defines event handler attributes like onclick
but there is nothing offical currently saying that such attributes are
reflected in the HTML DOM as properties. Browser implementations however
have always done so and exposed such an event handler as a function
object. So doing
this.onclick = function (evt) { /* function body here */ };
or
this.onclick = new Function ("evt", "//function body here");
where this is a HTML element object is fine.

The W3C DOM Level 2 Events module however defines addEventListener so
following that (where supported, IE 5/6/7 does not) you can do e.g.

function aClickHandler (evt) { /* function body here */ }

this.addEventListener(
'click',
aClickHandler,
false
);

to set and

this.removeEventListener(
'click',
aClickHandler,
false
);

to remove.
 
T

TheBagbournes

yawnmoth said:
Say I wanted to assign something to this.onclick. I could do this by
doing "this.onclick = Function('...')", but I'm not sure if that's the
prefered way to do it, per the official W3C specs?

Not all browsers conform to teh W3C specs. To do it in a cross-browser way, Use the YAHOO Event object from the YAHOO UI: http://developer.yahoo.com/yui/

And then use

YAHOO.util.Event.addListener(myDomElement, "click", myFunction, scopeObject, true);

That will attach the function myFunction, and call it in the scope of scopeObject.

Nige
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,483
Members
44,902
Latest member
Elena68X5

Latest Threads

Top