Chovy’s Blog

Javascript: Dynamically Change onclick Event

Sun, November 6, 2005 — Category: Development

Brief summary of how to properly add an event in javascript dynamically.

To dynamically change or add an “onclick” event handler to an element, try:


var el = document.getElementById('foo');
el.onclick = showPopup;
//NOTE: showPopup();
//or showPopup(param);
//will NOT work here.
//Must be a reference to a function,
//not a function call.

function showPopup() {
  var popup = window.open(this.href, "popup", "height=800,width=600");
  popup.focus();
  return false;
}
  • Post Javascript: Dynamically Change onclick Event to del.icio.us
  • Post Javascript: Dynamically Change onclick Event to digg
  • Post Javascript: Dynamically Change onclick Event to Furl
  • Add Javascript: Dynamically Change onclick Event to YahooMyWeb
  • Simpify!
  • Post Javascript: Dynamically Change onclick Event to shadows
  • Post Javascript: Dynamically Change onclick Event to Spurl
  • Post Javascript: Dynamically Change onclick Event to BuddyMarks
  • Submit Javascript: Dynamically Change onclick Event to Slashdot

39 Comments »

Comment by Tausif

July 17, 2006 @ 4:45 pm

If I have a method with a parameter then how will I dynamically bind it to the onclick event? Lets say my method is:

function showPopup(param)
{
alert(param);
}

Comment by chovy

July 18, 2006 @ 10:48 am

it only works with a function reference, which means you\’re not actually calling it, so there\’s no reason to pass it a parameter.

You probably need a different solution, if you tell me what you\’re trying to do, maybe there is a better way.

Is it possible to grab the data you need without passing it as a parameter? Find out where that parameter actually gets defined, and then just read it from inside your function, rather than trying to pass it dynamically.

Comment by Heucuva

August 19, 2006 @ 5:42 pm

You can call the following in order to change an onclick to actual script text:


node.attributes[”onclick”].value = “script_text_here()”;

Where “node” is the name of your document node that you want the onclick to be changed for. This works on all attributes like ondblclick and onmouseover, too.

Comment by ugur

August 20, 2006 @ 6:30 am

Heucuva,
I tried your solution but I can only get the value of onclick event, but I can’t set the value of onclick event.
I mean when trigger,
node.attributes[”onclick”].value = “script_text_here()”;

my elements onclick event doesn’t change to “script_text_here()” and I get no errors.

does it make sense ?

Comment by Lin

August 24, 2006 @ 10:04 am

you can use

element.onclick = function() {your_func_with_param(params)}

HIP

Comment by Chris S

October 10, 2006 @ 6:44 am

This works fine in IE but fails in Mozilla (Firefox). Any ideas?

Comment by Chris S

October 10, 2006 @ 7:39 am

Ignore previous comment, it was something else failing.

Comment by Dominic

October 13, 2006 @ 12:42 pm

Thanks! Was searching all through google to find out why my onfocus function could run. ur article certainly saved me a LOT of time!

Comment by Pat Welborn

October 13, 2006 @ 9:21 pm

Thanks for this illuminating bit of Javascript. This just saved HOURS of lost time.

Comment by i

November 12, 2006 @ 3:19 pm

Thaks :) that’s what i needed!

Comment by required

November 23, 2006 @ 2:50 pm

I cannot thank you enough.

From; a newbie…

Comment by xshape

December 4, 2006 @ 6:25 am

well done buddy!
THANKS ;)
That was what i needed too!

Comment by ilija

January 31, 2007 @ 8:22 am

Hi I have a different problem.
I want to assign onclick event to elements and I am getting a parametar from a XML file, but all of my parameters end up beeing the same as the las one!

for (var i=0;i
any idea?

Comment by chovy

January 31, 2007 @ 8:57 pm

you lost me there Ilija.

You’re getting a “parameter” from an XML file? not sure what you mean.

if you want to iterate over your xml elements, and apply an event handler to the elements, you need to loop over all the childNodes, and test for nodeType == 1 (el node type); then apply the event you want, otherwise continue in your loop.

Comment by ilija

February 1, 2007 @ 3:59 am

Sorry not all of my code pasted ??

This is my problem: I have parameters in XML and I loop through them, and then my parameter is OK, but when I write it to my dovcument all list elements recieve the last parameter.
In a xml document I have two elements, first one the the parameter and second one the text.
code:
for (var i=0;xml.length++;i++)
{
var link = getNodeValue(xml[i], ‘link’);
var text = getNodeValue(pretraga[i],’text’);
vali=li[i] = document.createElement (”li”);
}

Comment by ilija

February 1, 2007 @ 4:02 am

li[i] = document.createElement (”li”);
li[i].onclick function (sendRequest (”GET”, “index.php?p=” + link;

}
li is a list element which I append to some ul element.
All of my onclick event do the same.

Comment by ilija

February 1, 2007 @ 7:04 am

Sorry, but I am not sure my comment was posted !?
This is my problem. Because I am in the loop when I send a parameter it always references the last one.
var link;
var x=…. an Array I get from XML
for (i=0;i

Comment by Kashif

September 3, 2007 @ 12:09 am

I have tried the solution given above, actually my problem is that i have to increment row in a table having 3 textbox, and when this row is created i have to use ajax on onkeyup event to show that the data entered in these texboxes is valid or not, for this i took a div beside to every textbox to show if data is valid or not for this i call the function in which i use ajax work on onkeyup event. For this I have to pass parameters i.e. div id and and a counter dynamically to the function bcoz row is created dynamically on onclick event.
I hope u all got what i want…
thnx

Comment by Shadow

September 15, 2007 @ 5:00 am

I have diffrent problem.

var oForm = document.getElementById(’my_form’);

for(var i=0; i

Comment by Basan

November 6, 2007 @ 5:49 pm

About setting the onclick event on the fly (dynamically), YOU THA MAN! VERY NICE! CHEERS

Comment by chad

November 13, 2007 @ 11:30 am

I’m having similar problems to ilija above. When you iterate over a loop and dynamically create elements with javascript, you may not know ahead of time what your values are going to be. Those values are stored in arrays, for example, and when you set someElement.onclick = function(){somefunction(myvar[i]); } myvar[i] is (I think) out of scope when the function is actually called. what you end up getting is the last value put into the myvar array for every call to somefunction.

Trackback by Anonymous

December 26, 2007 @ 9:48 pm

blowjob blond cum

blowjob blond cum

Comment by jonyBgood

December 27, 2007 @ 2:42 am

god bless you! saved my day!

Comment by wonder

January 4, 2008 @ 1:01 pm

LIN, thank a lot, you save me a lot of time.

Comment by jalil

January 7, 2008 @ 2:53 am

element.onclick = function() {click_ack();}

fails in IE6, work in FF.
any ideas please?

Comment by jalil

January 7, 2008 @ 3:03 am

my apologies.

element.onclick = function() {click_ack();}

*does* work in both IE and FF. great !
( i put it in the wrong place initially ).

incidentally, FF works with this too…

element.setAttribute(’onClick’,'click_ack()’);

but not in IE.

interesting how an attribute can also carry an event, in a sense they are the same, so FF is correct.

thanks much.

Comment by David Xu

January 9, 2008 @ 9:19 am

I want to set this dynamically
link

this doesn’t work, since event var is not found.
aa.onclick = function() {wrapContent(event, aa.href);}

this works for FF only
aa.setAttribute(”onClick”,”return wrapContent(event, this.href)”);

Please help

Comment by David Xu

January 9, 2008 @ 9:22 am

I want to set this dynamically
onClick=”return wrapContent(event, this.href)” to links.

Following doesn’t work, since event var is not found.
aa.onclick = function() {wrapContent(event, aa.href);}

this works for FF only
aa.setAttribute(”onClick”,”return wrapContent(event, this.href)”);

Please help

Comment by Kishor

January 29, 2008 @ 10:54 pm

Hi all,

I’m using oops concepts of javascript in which i’ve a class and some methods. I one method I’m creating few html elements (like DIV, IMG) for a particular object and now I want to assign some event (mouse) on image used. This is goining to be dynamically adding of events. Is it possible to have the normal function defined in the class method?
Any ideas?

Trackback by Viagra.

February 8, 2008 @ 5:44 pm

Viagra….

Viagra….

Comment by CarolinaCool

February 10, 2008 @ 12:34 pm

Thanks for the info!! It worked like a charm for setting the onclick attribute dynamically.

Comment by Lucio

March 7, 2008 @ 2:35 am

Wonderful. Worked like a charm. Thanks.

Trackback by cingular go phone ringtones

March 7, 2008 @ 7:30 am

downloadable free mobile ringtones downloadable free mobile ringtones t…

However free phone ringtones verizon wireless application loan payday…

Trackback by free ringtones creator software

March 8, 2008 @ 9:00 am

free ringtones for nextel phone…

All approval guaranteed loan payday free real ringtones for alltel…

Trackback by free sony ericsson ringtones

March 8, 2008 @ 9:15 am

downloadable cell phone ringtones…

Pay faxless instant loan payday ericsson polyphonic ringtones sony…

Trackback by cash till payday loan

March 8, 2008 @ 10:12 am

pay day loan cash advance…

With the first american cash advance pre settlement cash advance…

Trackback by sito poker

March 8, 2008 @ 12:47 pm

giocare poker online…

Mai poker play money giochi omaha poker gratis…

Trackback by gioca poker on line

March 8, 2008 @ 1:23 pm

bet online poker…

Questi poker flash on line scarica giochi poker…

Comment by ethan

April 20, 2008 @ 11:52 am

Thank you!
I’ve been trying to make this work for hours

//NOTE: showPopup();
//or showPopup(param);
//will NOT work here.
//Must be a reference to a function,
//not a function call.

but I was missing this key bit of info.
You just made my day.
Thank you.

RSS feed for comments on this post. TrackBack URI

Leave a comment

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

 
Keyword Advertisers:
SEO Directory SEO Links Free Link Directory Shopping Submission Directory Gardening Tips Political Forum Search Engine Optimization Search Engine Marketing Audio Video Directory SEO Forum Web Development Blog Organic SEO Wiki Web Development Consulting

Learn more about purchasing keyword text link ads on this site.