views:

73

answers:

5

I have link that calls a function when clicked:

<a href="javascript:spawnMenu(this);" id="link1">Test1</a>

To make my function work, I need access to the object so that I can perform jQuery operations like this:

alert($(objCaller).offset().left);

Since objCaller points to the object and not the object ID, this won't work. I need something like this:

alert($("a#link1").offset().left);

How can I get the object ID from objCaller?

+2  A: 

Doesn't this work?

objCaller.id
tloflin
`<a href="javascript:alert(this.id);" id="link1">Test1</a>` returns `undefined`.
Pieter
Oh, yeah, that's because you can't pass `this` in an href. Pass it via the `onclick` event instead.
tloflin
+3  A: 

You need to do this:

<a href="javascript:;" onclick="spawnMenu(this);" id="link1">Test1</a>

You can't pass this via a javascript: url.

Rob
A: 

Just off the top of my head: does alert($(this).offset().left); not work? Otherwise, you can get the ID via $(this).attr("id").

Todd
See Rob's answer below. I didn't even look at that part of the issue.
Todd
A: 

It's not clear from your question what objCaller refers to. If it refers to the element itself, then $(objCaller) would work fine with jQuery.

Try your code using firebug (an extension for firefox). You can swap 'alert' for 'console.log' so you have:

console.log(objCaller);

This will help you work out exactly what is stored in objCaller (it isn't an element if $(objCaller) isn't working, as I say).

If objCaller is an element, then objCaller.id would be the way to retrieve the id.

adamnfish
A: 

You can get the ID by doing this:

function spawnMenu (elem) {
    var id = elem.id; // elem is just a DOM node, so access it's id

    // your code here...
}

However, jQuery should also be able to wrap a DOM node, so the following should work as well:

function spawnMenu (elem) {
    elem = $(elem).get(0);

    // your code here...
}
Bialecki