DelphiFAQ Home Search:

How do I add a javascript event handler on the fly (at runtime)?

 

comments14 comments. Current rating: 4 stars (5 votes). Leave comments and/ or rate it.

Question:

I need to attach an event handler at runtime, the idea is that depending on user action, I want different handlers to be assigned. But it seems not to work?

Answer:

Below is some javascript code that will work. It was tested with Firefox and IE 6. It seems not to be possible to assign the handler in the links' onclick() itself e.g.

href="javascript:document.sampleImage.onclick=Handler1; "

does NOT work! Common other errors are to actually call the event handler in the assignment statement by appending the () or to write the to-be-assigned event handler as a string (encapsulating it with " or ').

Assigning in a function body as shown below works as expected.

<html>
<body>
<img name="sampleImage" width=30 height=20 border=1 src="someimage.gif"><br>

<script language="JavaScript" type="text/javascript">
<!--
function Handler1 (evt) {
  alert('clicked image (1)'); 
}

function Handler2 (evt) {
  alert('clicked image (2)'); 
}

function assign_handler_1() {
  document.sampleImage.onclick=Handler1;  
}
function assign_handler_2() {
  document.sampleImage.onclick=Handler2;
}
// end hiding contents -->
</script>

<a href="javascript:assign_handler_1()">activate handler 1</a>
<br>
<a href="javascript:assign_handler_2();">activate handler 2</a>

</body>
</html>

Content-type: text/html

Comments:

2006-04-20, 07:58:11
chauhansudhir@gmail.com from India  
rating
<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4Transitional/ /EN'>
<HTML>
<HEAD>
<TITLE&LE> New Document </TITLE>
<META NAME='Generator' CONTENT='EditPlus'>
<META NAME='Author' CONTENT=''>
<META NAME='Keywords' CONTENT=''>
<META NAME='Description' CONTENT=''>

<SCRIPT LANGUAGE='JavaScript'>

    function changebox()
    {
        var obj = document.getElementById('changelable');
        if(!document.getElementById('d'))
        {
            var d = document.createElement('select') ;
            d.id= 'dsel';
            d.name = 'dsel';
            d.setAttribute('onChange','alerthere(this.id);');
            doption = document.createElement('option');
            d.appendChild(doption);
            doption.appendChild(document.createTextNode('dsel'));
            obj.appendChild(d);
            d.options[1] = new Option ('sd','sd');
            d.options[2] = new Option ('sd1','sd1');

            var btn = document.createElement('input');
            btn.type='submit';
            btn.id= 'testbtn';
            btn.value= 'Click here';
            btn.name= '1testbtn';
            btn.setAttribute('onclick','alerthere(this.id);');
            obj.appendChild(btn);
        }
    }
    function alerthere(evt)
    {
        alert('here');
    }

</SCRIPT>
</HEAD>
<BODY>
    <div id='changelable'><a href='#' onClick='javascript:changebox();'>Click Here</a></div>
</BODY>
</HTML>
2006-04-20, 16:59:53
anonymous from United States  
Hello, chauhansudhir@gmail.com:

Seems that this line does not work, at least not in IE:

btn.setAttribute('onclick','alerthere(this.id);');

If you change it to this, it will work, but you cannot pass the argument:

btn.onclick=alerthere;
2007-02-14, 19:51:31
anonymous from Malaysia  
hi, use this

function alerthere(ss)
{
alert(ss);
}

var str = 'Hello 3';
btn.onclick=function(){alerthere(str)};
2008-04-17, 09:42:13   (updated: 2008-04-17, 09:43:52)
anonymous from Mexico  
'QUOTE'
hi, use this

function alerthere(ss)
{
alert(ss);
}

var str = 'Hello 3';
btn.onclick=function(){alerthere(str)};
'END OF QUOTE'
wow thanks i was looking for a way to do that and this is it!
2008-06-14, 09:45:29
anonymous from United Kingdom  
rating
nice
2010-02-15, 08:56:10
anonymous from United Kingdom  
Thank you.
The above solution works in IE 6.0 !.....
2012-06-30, 01:52:52
anonymous from China  
2012-06-30, 01:54:06
anonymous from China  
2012-06-30, 01:55:15
anonymous from China  
2012-07-23, 22:42:24
anonymous from United States  
2013-02-05, 10:56:04
 
rating
wshwllps <a href=' http://genericviagratd.com/ '>generic cheap viagra online</a> >:]] <a href=' http://genericcialistd.com/ '>generic cialis</a> %-[[[
2013-02-14, 23:46:15
 
rating
wuwqefks <a href=' http://paydayloansvbd.com/ '>quick payday loans</a> >:-[ <a href=' http://paydayloansvbd.ca/ '>payday loans</a> TBqUMO <a href=' http://paydayloansvbd.co.uk/ '>pounds till payday</a> 9968
2013-02-18, 00:44:15
 
rating
vfabtmbw <a href=' http://orderviagrafsb.com/ '>order 50mg viagra</a> hsoCk <a href=' http://ordercialisfsb.com/ '>cheapest place to order cialis</a> 0294
2015-02-01, 04:18:40
anonymous from United States  
I can't believe you're not playing with me--ahtt was so helpful.

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: