DelphiFAQ Home Search:

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

 

comments16 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:

You are on page 1 of 2, other pages: [1] 2
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-18, 21:39:18
anonymous from Colombia  
One alleged victim would routinely throw away his underwear to hide [url= http://www.louisvui..net/]Louis Vuitton Bags[/url] the supposed abuse. Week two of the trial began with a final prosecution witness. The mother of Victim No. 9 took the [url= http://www.chanelou..et/]Chanel Purses[/url] stand Monday to detail her son’s cover-up of the alleged sordid acts he suffered at Sandusky’s hands. “I [url= http://www.guccibel..rg/]Hermes Belts[/url] always wondered why he never had any underwear in the laundry,” she testified. “He just told me he had an [url= http://www.beltsout...org/]Mens Belts[/url] accident and he threw them out.” Indeed, she testified that he started becoming “sick” more often after [url= http://www.topbelts..org/]Gucci Belts[/url] spending time with the ex-Penn State coach. Victim No. 9 supposedly slept over at the Sandusky residence more than 100 times.Victim No. 9 testified [url= http://www.louisvui..net/]Louis Vuitton Handbags[/url] last Thursday that he screamed during one episode of alleged abuse, hoping that [url= http://www.beltsonl..com/]Louis Vuitton Belts[/url] Sandusky’s wife, who he said was always upstairs, would hear. “I think the basement is soundproof,” he said [url= http://www.chanels-..om/]Chanel Handbags[/url] tearfully, noting that Sandusky’s wife Dottie never did come down.Lead defense attorney Joe Amendola has also [url= http://www.chanelba..om/]Chanel Handbag[/url] suggested previously that the accusers and the Attorney General’s office might be colluding. Lead prosecutor Joe [url= http://www.lvshopos..net/]Louis Vuitton Purses[/url] McGettigan has often queried the alleged victims while on the stand: “Have I ever, ever, ever told you what to say?” which they’ve answered with resounding denials. But it could be a larger issue for Kline and the other subpoenaed attorneys to defend themselves against a [url= http://www.louisvui..com/]Louis Vuitton Purse[/url]
charge of violating the gag order issued by Judge Cleland, which bars any representative from either side from discussing the case with the media.


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.
You are on page 1 of 2, other pages: [1] 2

 

 

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: