if no "onmouseover" in HTML, how can javascript do an link id - dependent action?

M

metasilk

Situation:
Many links with hrefs & some have ids in the HTML.
External javascript file.

Wanted:
When the mouse is hovering over a link with a certain id, do something
(such as display one particular image; which image depends on which
link).
Do this without having onmouseover attributes in the HTML.

Question:
Can I use addEventListener/attachEvent to make the script perceive
WHICH link is hovered over, and feed that link's id to some variable?
If so, HOW?

Note: If I specify "look for this link" (with
document.getElementById('link_id'), the script can listen for the
event. However, when I have more than one specified link_id, only the
last one has any effect. Also, if I write a for loop, so far the same
issue (only the last id has any effect, all the rest are ignored).

Hope this makes sense.

--metasilk
 
M

Michael Winter

[snip]
Can I use addEventListener/attachEvent to make the script perceive WHICH
link is hovered over, and feed that link's id to some variable?

It's possible with addEventListener, but not with attachEvent. I'll
explain in a moment.
If so, HOW?

Just like with intrinsic events specified in HTML, the this operator
refers to the element to which the listener is attached. Once you have a
reference to the element, you can get the id attribute. A demo can be
found at:

<URL:http://www.mlwinter.pwp.blueyonder.co.uk/clj/metasilk/this.html>

So, why won't this work with attachEvent? Because IE doesn't set the this
operator properly. Instead of referencing the element, it used the global
(window) object. To get around this, you can fall back onto the old,
on<event name>, properties if addEventListener isn't available.

Just in case you didn't know, the old event properties don't allow you to
add multiple listeners to a single element without a lot of extra code. On
top of that, any existing listeners specified in the HTML will be
overridden:

<span id="test" onclick="alert('foo');">Test</span>

Clicking the above will display "foo" as expected, but:

<span id="test" onclick="alert('foo');">Test</span>

document.getElementById('test').onclick = function() {
alert('bar');
};

the above result in "bar". If you used addEventListener, you would get
both (foo, first).

That "extra code" is used by the demo above.

[snip]

Hope that helps,
Mike
 

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

Forum statistics

Threads
473,769
Messages
2,569,581
Members
45,057
Latest member
KetoBeezACVGummies

Latest Threads

Top