DelphiFAQ Home Search:

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

 

comments5 comments. Current rating: 5 stars (2 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>

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

 

 

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.
 
It seems that you are
from Washington, US .

Info/ Feedback on this

Show city and country
Show country only
Hide my location
Leave your comment here:
Please type in the code:
photo Add a picture:

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.