cc young
cc young

Reputation: 20213

In Firefox, get href of anchor in onclick trigger

With the following html:

<div>
   <a href='#link1' onclick='func()' >Link 1</a>
   <a href='#link2' onclick='func()' >Link 2</a>
   <a href='#link3' onclick='func()' >Link 3</a>
</div>

function func() {
   var href = ??;
   if( href.match(/#link1/) ) {
      ...
   }
}

in Chrome (and IE?) can use this code

var href = window.event.target.href;

but window.event does not exist in Firefox

If the events were attached via addEventListener then could have e as an argument, but see no way to get the event passed to the onclick function when declared in html.

Upvotes: 1

Views: 2001

Answers (2)

Boris Zbarsky
Boris Zbarsky

Reputation: 35064

You do get the event as an argument, in the onclick handler itself. So you can do:

 <a href="#link1" onclick="func(event)" >Link 1</a>

and then you can look at the event target in func.

Upvotes: 1

mrtsherman
mrtsherman

Reputation: 39872

Pass in this to your function and then directly access the href property. this will refer to the element that made the call. You may also want to return false - this prevents the clicked link from navigating.

http://jsfiddle.net/qjXVy/

function func(elem) {
    alert(elem.href);
    return false;
}

 

<div>
   <a href="#link1" onclick="func(this)" >Link 1</a>
   <a href="#link2" onclick="func(this)" >Link 2</a>
   <a href="#link3" onclick="func(this)" >Link 3</a>
</div>

Upvotes: 4

Related Questions