Abhradip Abhradip - 4 months ago 13
HTML Question

Issue regarding javascript onclick

I am creating a link tag

(anchor tag)
dynamically using javascript. There is a javascript function which will be fired by an event and it will create a javascript link.

I have already mentioned the required attributes for the newly created anchor tag using javascript. Now I have also mentioned an onclick event on that anchor tag.

The problem is that the onclick event is fired during the anchor tag creation. And it is firing for that one time. Next time when I am clicking on the link,I am unable to get my desired result.

javascript code:

function waybill()
var mail_link=document.createElement("a");
mail_link.className='animated bounceInDown';
mail_link.innerHTML="Mail Waybill";
var holder_div=document.getElementById("holder");
function abc_test()
alert("mail link clicked");

I am getting the alert only once and without even clicking.
Please help me.


mail_link.onclick = abc_test() will invoke abc_test and assign its return value to mail_link.onclick.

If you just want to reference the function, and not call it, leave out the ():

mail_link.onclick = abc_test;

Adding event listeners is one of those things that a lot of old browsers are doing in their own way, and it's a bit messy to add support for all of them. Sicnce the question is tagged jQuery, you could do all of this in jQuery and have browser support handled for you:

$('<a/>', {
   href: 'javascript:void(0);',
   'class': 'animated bounceInDown',
   text: 'Mail Waybill',