Ramesh
Ramesh

Reputation: 2337

How to get the action performed by an hyperlink in javascript

How can i get the action performed by an hyperlink inside an div using javascript

<div id="example">
<a href="#">a<a>
<a href="#">b</a>
<a href="#">c</a>
</div>

Upvotes: 1

Views: 763

Answers (4)

Alex Dn
Alex Dn

Reputation: 5553

$("#example a").click(function() {
    alert("action");
});

Upvotes: -1

meouw
meouw

Reputation: 42140

@Headshota example of referencing all the links within a div is reasonable, I'm merely expanding on it. I'm not sure what you mean by the action of a link so I'm assuming that you mean the url it points to and perhaps the target (deprecated).

var links = document.getElementById('example').getElementsByTagName('a');

links[0].onclick = function(){

    // `this` inside this handler points to the <a> element that has been clicked
    var href = this.href //where the link points
    var target = this.target //if required

    //do something with href and target

    return false; //don't follow the link
}
etc...

Upvotes: 0

Headshota
Headshota

Reputation: 21449

var links = document.getElementById('example').getElementsByTagName('a');

links[0].onclick = function(){
  alert('a clicked');
}

links[1].onclick = function(){
  alert('b clicked');
}

links[2].onclick = function(){
  alert('c clicked');
}

Working Example

you can attach event handlers in the loop as well:

var links = document.getElementById('example').getElementsByTagName('a');
    for(var i = 0;i < links.length; i++){
        links[i].onclick = function(e){
            var event = e || window.event;                    
            alert(e.target.innerHTML + ' link was clicked!!!');
        }
}

Upvotes: 2

Starx
Starx

Reputation: 79069

I am guessing you are coming from a java background. So, action performed is not available by default in JavaScript. Neither is an anchor or <a>, an anchor is generally used to link to an external or internal links.

<a href="mypage.html"> Goes to a mypage.html </a>

Where As what you are asking by action performed is events. For that you should do something like this

<a href="#" onclick="test();">Test Link </a>

What this above link does is, executes a javascript function name test();

function test() {
    alert('ok the action is performed'); 
    return false; //so that the browser does not decides to navigate after the function is executed
}

Some javascript libraries will give you some workaround for this. Here is an basic example done in JQuery

$("#example a">.click(function() {
   //now you have got the action performed work around. 
   // You can use this as you like
   // $this represent the item that was clicked
});

For this functionality in core. @Headshota answers is good example.

Upvotes: 0

Related Questions