473,732 Members | 2,201 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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="doClic k(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('eve nt','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><ti tle>DynFunc</title>
<script type="text/javascript">
function initButton() {
var ele = document.getEle mentById('theBu tton');
ele.onclick = function (){doClick('eve nt','this')};
}

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

--
Rob
--
Rob
Jul 23 '05 #1
2 18580
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="doClic k(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.oncli ck = function(){
doClick (event,x);
};

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

buttonRef.oncli ck = 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('eve nt','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('eve nt','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
44978
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 dynamically like:
3
12485
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 have the following event handler functions defined and need to assign them to table elements (<TD>) created dynamically in another function. function handleMouseOver(elt, cssClass, strURL)
8
9561
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 1. 1. find the <tr> that I will insert <tr>s right after it
4
2265
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 source:
9
2206
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 pre_act="confirm" to all of the links that i wanted to do this to and am trying to add an onclick event that will cancel the click action if they fail. I've got a test page at http://randomwebspace.net/testing/testpage.html. It has no unintentional XHTML...
11
11209
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 struggling getting an onClick event to show in the HTML source. Any help would be appreciated. Here is a block of my current code which doesn't work. var tr1 = document.createElement('tr');
7
2531
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 several methods that are working fine. The problem is if I want to dynamically assign an event handler to the object, the event handler is not called. What am I doing wrong? Below is a sample HTML doc with everything in place. <!DOCTYPE HTML PUBLIC...
3
3031
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 line document.getElementById('div1').setAttribute('oncontextmenu', someText); to document.getElementById('div1').setAttribute('oncontextmenu', function(){alert('World World');return false;});
4
2022
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 element to have an onclick that calls another function. So it looks like this: function dynamicallyCreateElement() { .... element.onclick = myFunction;
0
8946
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
9447
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
9235
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
9181
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
8186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2721
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.