January 6, 2012

How to get the action performed by an hyperlink in javascript

Question by Ramesh

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>

Answer by Headshota

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!!!');
        }
}

Answer by Starx

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.

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!