473,395 Members | 2,689 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,395 software developers and data experts.

Dynamically adding onclick to element

I am trying to dynamically add an onclick to an element,
however I just can't get the syntax right. consider the
following function:

function doClick (evt,x) {
// do things with evt and x
}

Which is called statically by:
<button onclick="doClick(event,this);">Click me</button>

evt should be a reference to the onclick event, and x to the
element clicked on. But I can't get the syntax right for adding
the element dynamically. The closest I can get is:

ele.onclick = function (){doClick('event','this')};

But when I click on the element, 'event' and 'this' have been
passed is literal strings (i.e. e and x are 'event' and 'this',
literally).

What is the correct syntax?

*Extra comment*

I have tried adding the function this way:

ele.onclick = doClick;

And then use e/window.event to get the event and use
e.target/e.srcElement to get the element clicked on, but that is
not reliable with some browsers. For example, in Safari if you
have an onclick on a TD with text in it and the user clicks on
the text, e.target points to the text node, not the TD. If they
click in the TD but not over the text e.target points to the TD.

This is avoided if the onclick passes 'this', which
unequivocally (I think) gives a reference to the element that
the onclick fired from.

Of course I can climb the DOM tree to find the first onclick and
hope that was the one that fired, but that's messy. It also
creates an issue if there's a link in the cell. Other browsers
will follow the link and not execute the onclick - Safari does
the onclick. Again, I can look to see if target was an A and
follow the link by changing the window.location, but again,
that's messy.

Play code below.

<html><head><title>DynFunc</title>
<script type="text/javascript">
function initButton() {
var ele = document.getElementById('theButton');
ele.onclick = function (){doClick('event','this')};
}

function doClick(evt,x) {
alert('evt is: ' + typeof(evt)
+ '\nx is: ' + typeof(x));
}
</script>
</head><body>
<button onclick="initButton();">Initialise theButton</button>
&nbsp;
<button id="theButton">theButton</button>
&nbsp;
<button onclick="doClick(event,this);">Static onclick</button>
</body></html>

--
Rob
--
Rob
Jul 23 '05 #1
2 18531
RobG wrote:
I am trying to dynamically add an onclick to an element,
however I just can't get the syntax right. consider the
following function:

function doClick (evt,x) {
// do things with evt and x
}

Which is called statically by:
<button onclick="doClick(event,this);">Click me</button>
Disregarding the custom scope chain code, specifying event handler code
in the string value of an attribute results in the browser creating an
event handling function and assigning it as a method of the DOM element
in question. In IE it is equivalent to:-

buttonRef.onclick = function(){
doClick (event,x);
};

While in Mozilla/Gecko and other browsers that follow the Netscape style
you get a function like:-

buttonRef.onclick = function(event){
doClick (event,x);
};

- created and assigned. Notice that the Netscape style has a function
with a formal p0arameter called - event -. So the Netscape style event
handler passes whatever value is passed as an argument to the event
handler function on to your doClick function, while the IE version
resolves the unqualified Identifier - event - against the scope chain
and finds the - window.event - object in the global scope. This allows
attribute code to use the same identifier to pass on the event object.
<snip> ele.onclick = function (){doClick('event','this')};

But when I click on the element, 'event' and 'this' have been
passed is literal strings (i.e. e and x are 'event' and 'this',
literally).
If you put quotes around the identifiers/keywords they will be string
literals.
What is the correct syntax?
ele.onclick = function (e){doClick((e||window.event),'this')};

- will do.
*Extra comment*

I have tried adding the function this way:

ele.onclick = doClick;
With:-

function doClick(e){
e = e || window.event;
// do things with e and this,
// as - this - will refer to whichever element this function
// is assigned to as a method (- ele - in that case).
}

- that would work fine.
And then use e/window.event to get the event and use
e.target/e.srcElement to get the element clicked on, but that is
not reliable with some browsers.
The actual event handling function (either created by the browser or
assigned as a property of the element with a script) is executed as a
method of the DOM element and under those circumstances the - this -
keyword is a reference to that object (the DOM element).
For example, in Safari if you
have an onclick on a TD with text in it and the user clicks on
the text, e.target points to the text node, not the TD. If they
click in the TD but not over the text e.target points to the TD.

This is avoided if the onclick passes 'this', which
unequivocally (I think) gives a reference to the element that
the onclick fired from.

<snip>

Depends on what you mean by 'fired from'. If you mean the source of an
event that is processed when captured or bubbling (rather than at its
target) then no it doesn't necessarily refer to the target. It refers to
the element with which the handler function is associated (as a method).

Richard.
Jul 23 '05 #2
Richard Cornford wrote:
[...]
<snip>
ele.onclick = function (){doClick('event','this')};

But when I click on the element, 'event' and 'this' have been
passed is literal strings (i.e. e and x are 'event' and 'this',
literally).
If you put quotes around the identifiers/keywords they will be string
literals.
What is the correct syntax?


ele.onclick = function (e){doClick((e||window.event),'this')};

- will do.


Yuck, not for me! I think I can work out what is going on, but it
makes my brain hurt. For my purpose the simplicity of:

ele.onclick = doClick;

is very appealing. e & this are then handled in the function with:

function doClick(e,x) {
e = e || window.event;
x = x || this;

doClick can now be called from either dynamic or static onclicks
quite happily (only tested in IE & Firefox, Safari will have to
wait...)
Thanks for the shorthand "OR" method, I was using:

if (!e && window.event) var e=window.event;
if (!x && this) var x = this;
*Extra comment*
[...] function doClick(e){
e = e || window.event;
// do things with e and this,
// as - this - will refer to whichever element this function
// is assigned to as a method (- ele - in that case).
}

- that would work fine.


I actually worked that out after posting - funny how you can struggle
with something for ages, then as soon as you post...

I still have an awful lot to learn about JavaScript and functions in
particular (DOM stuff is a snap by comparison), thank you for the
excellent tutorial. Hopefully some of it will sink in...

--
Rob

Jul 23 '05 #3

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: Michael Hill | last post by:
I had this html: <tr id="action" title="click to do something" onclick="alert('mike');"> <td>a</td> <td>b</td> </tr> and it works when I click on the row, but when I try to add it...
3
by: N. Demos | last post by:
How do you dynamically assign a function to an element's event with specific parameters? I know that the code is different for MSIE and Mozilla, and need to know how to do this for both. I...
8
by: cool2005 | last post by:
I tried to dynamically add/clone a <tr> from an existing <tr> to a <table> but the problem is that I need to have a "onclick" event handler in the <tr>. I have tried following A. approach...
4
by: RobG | last post by:
I have a function whose parameter is a reference the element that called it: function someFunction(el) { ... } The function is assigned to the onclick event of some elements in the HTML...
9
by: Donius | last post by:
Hey everyone, i am doing some stuff where i'd like to pop up a little confirmation before a user clicks on a 'delete' link. Just trying to keep the markup clean, i added an attribute ...
11
by: Daz | last post by:
Hello everyone. I am sure the answer to my question is simple, but I can't seem to dynamically add an onClick event to my script. I have a table which is generated dynamically, I am just...
7
by: Ron Goral | last post by:
Hello I am new to creating objects in javascript, so please no flames about my coding style. =) I am trying to create an object that will represent a "div" element as a menu. I have written...
3
by: ICPooreMan | last post by:
The following is a very simple example of what I want to do take an elements oncontextmenu and changing it dynamically onclick of that same element. The code below will fail unless you change the...
4
by: shuchow | last post by:
Hi, sorry for the basic question, but can someone explain to me some basic event attachment process. Say I have a function, dynamicallyCreateElement(), that creates an element. I want that new...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.