Forum Moderators: open

Message Too Old, No Replies

Passing object reference from a href

         

garann

5:48 pm on Sep 12, 2005 (gmt 0)

10+ Year Member



I can't believe I've never run into this problem. I'm trying to call a function and pass it a reference to the object that's calling it, in this case an anchor tag. My original code looked like this:

<a href="javascript:toggleDisplay(this)">click here</a>

I was surprised to see that the object the function received was a reference to the browser window (?). This is in Firefox. If I call the function from

onclick
, it works! Am I doing something wrong, or has Javascript behaved this way all along and I just never noticed it before?

Thanks in advance for any help!

Bernard Marx

6:33 pm on Sep 12, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



What you see is correct. This behaviour isn't often mentioned. The way I see it, an event handler (onclick et al) defines a binding to an anonymous function

<div onclick="alert(this)">
// or
myDiv.onclick = function(){ alert(this) }

Meanwhile, an href simply redirects to an 'address' using the javascript protocol. The command could equally well be written in the address bar. The context remains global.

Many commentators are set against using the javascript protocol in hrefs anyway.

garann

6:46 pm on Sep 12, 2005 (gmt 0)

10+ Year Member



Thanks for the quick response!

What you see is correct. This behaviour isn't often mentioned.

Could you share a link to where you're getting this information? I need to do some research on this now...

Bernard Marx

7:40 pm on Sep 12, 2005 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Could you share a link to where you're getting this information?

I made it all up!

That is to say, I haven't read anything about this, just poked around in the browser as a "black box", and made assumptions.

Is there anything in particular you need to find out about?

garann

7:57 pm on Sep 12, 2005 (gmt 0)

10+ Year Member



No, nothing specific. This just clarified for me that it's time to refresh my JS knowledge. It's not a big deal. :)