473,761 Members | 7,351 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Attaching events to dynamically created elements

Hi, sorry for the basic question, but can someone explain to me some
basic event attachment process. Say I have a function,
dynamicallyCrea teElement(), that creates an element. I want that new
element to have an onclick that calls another function. So it looks
like this:

function dynamicallyCrea teElement() {
....
element.onclick = myFunction;

....
}

function myFunction() {
...

};

The problem is that myFunction will be called during the execution of
dynamicallyCrea teElement(), and not just the onclick for the element.

Instead, I have tod o this:
function dynamicallyCrea teElement() {
....
element.onclick = function() { myFunctions())_ ;;

....
}

Why does the first one automatically execute myFunction, and what
exactly does
element.onclick = function() do?
Jul 24 '08 #1
4 2024
SAM
sh*****@gmail.c om a écrit :
Hi, sorry for the basic question, but can someone explain to me some
basic event attachment process. Say I have a function,
dynamicallyCrea teElement(), that creates an element. I want that new
element to have an onclick that calls another function. So it looks
like this:

function dynamicallyCrea teElement() {
...
element.onclick = myFunction;
here you tell to execute the function

element.onclick = 'myFunction()'; // could work
}

function myFunction() {
};

The problem is that myFunction will be called during the execution of
dynamicallyCrea teElement(), and not just the onclick for the element.

Instead, I have tod o this:
function dynamicallyCrea teElement() {
...
element.onclick = function() { myFunctions())_ ;;
not exactly (see below)
}

Why does the first one automatically execute myFunction,
because that works like that
as it does if you do

window.onload = alarm;

function alarm() { alert('OK'); }

and what exactly does
element.onclick = function() do?

The last one, you assign an annonymous function that will call anothrer
one on element's event 'click'

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

element.onclick = 'myFunction();' ;

is same as

<tag onclick="myFunc tion();">
myFunction() would have to be declared outside of the function
dynamicallyCrea teElement

--
sm
Jul 24 '08 #2
SAM meinte:
sh*****@gmail.c om a écrit :
>Hi, sorry for the basic question, but can someone explain to me some
basic event attachment process. Say I have a function,
dynamicallyCre ateElement(), that creates an element. I want that new
element to have an onclick that calls another function. So it looks
like this:

function dynamicallyCrea teElement() {
...
element.onclic k = myFunction;

here you tell to execute the function
Err... What? A reference to a function is assigned to the onclick
property - nothing gets executed. element.onclick () would call the
function, or element.onclick = myFunction(); would assign the result of
myFunction to the onclick property.
element.onclick = 'myFunction()'; // could work
Yuck! And I doubt it "works" cross-browser.
>}

function myFunction() {
};

The problem is that myFunction will be called during the execution of
dynamicallyCre ateElement(), and not just the onclick for the element.
I doubt that. Could you provide a test case?
>Instead, I have tod o this:
function dynamicallyCrea teElement() {
...
element.onclic k = function() { myFunctions())_ ;;
Wrap your function into another anonymous function I suppose - the
result should be the same. However, your "{ myFunctions())_ ;;" will only
result in a syntax error.
>Why does the first one automatically execute myFunction,

because that works like that
as it does if you do

window.onload = alarm;
This executes alarm when the load event fires. Not when you assign the
function, which seems to be the "problem" of the OP. I suppose he only
forgot some parantheses.
element.onclick = 'myFunction();' ;

is same as

<tag onclick="myFunc tion();">
No.
myFunction() would have to be declared outside of the function
dynamicallyCrea teElement
No.

Gregor
--
http://photo.gregorkofler.at ::: Landschafts- und Reisefotografie
http://web.gregorkofler.com ::: meine JS-Spielwiese
http://www.image2d.com ::: Bildagentur für den alpinen Raum
Jul 24 '08 #3
On Jul 24, 5:35*pm, shuc...@gmail.c om wrote:
Hi, sorry for the basic question, but can someone explain to me some
basic event attachment process. *Say I have a function,
dynamicallyCrea teElement(), that creates an element. *I want that new
element to have an onclick that calls another function. *So it looks
like this:

function dynamicallyCrea teElement() {
...
element.onclick = myFunction;

...

}

function myFunction() {
..

};

The problem is that myFunction will be called during the execution of
dynamicallyCrea teElement(), and not just the onclick for the element.
No it won't; you're confusing

element.onclick = myFunction;

and element.onclick = myFunction();

C.
Jul 24 '08 #4
On Jul 24, 6:10*pm, "C. (http://symcbean.blogsp ot.com/)"
<colin.mckin... @gmail.comwrote :
ot just the onclick for the element.
>
No it won't; you're confusing

element.onclick = myFunction;

and element.onclick = myFunction();

C.
I think I meant element.onclick = myFunction(this ); in my original
code, which definitely does execute myFunction().

After reading Peter-Paul Koch's page about the "this" keyword (http://
www.quirksmode.org/js/this.html) I got a much better understanding of
what I needed to do. I needed handler functions that would work for
both adding events using .onclick and inline.

Inline is handled by <span onclick="editHa ndler(this)"and
element.onclick = editHandler; handles adding the event in the table
row creation function. Inside editHandler, "this" is references the
span that I'm clicking on, which is what I really needed in the first
place. Thanks for all the responses.
Jul 25 '08 #5

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

Similar topics

1
3193
by: Will | last post by:
Hi, I have a problem trying to validate dynamically created html form elements using javascript. I have dynamically created a check box using ASP for each record in a recordset and have given each a unique ID using the primary key from a db table. e.g "chk" + "1" for record 1 and "chk" + "2" for record 2 etc. This means each box is called chk1 and chk2 respectively. This works fine and changes dependant on the recordset used and allows me...
6
3334
by: Thomas | last post by:
Hi, I'm having a problem with the dynamically created inputfields in Internet Explorer. The situation is the following: - I have a dynamically created table with a textbox in each Cell. - It is possible to Add and Delete rows - Some cells have special attributes (readonly and events) Here's a snippet of the code:
5
2359
by: knocte | last post by:
Hello. I am a web developer very worried about "bloat code" and "languages mixture". So, since some time, I always try to avoid completely the use of javascript in XHTML/HTML files. This leads to me to hate, also, any event (onload, onchange, ...) instanciated in the element tag itself, like: <input type="text" onkeyup="return doSomething();" /> I would replace this code above with an input element marked with an
4
2561
by: blue | last post by:
I have a drop-down list, a radio button list and a submit button. I'm adding these controls to a table and I'm adding the table to a Placeholder. I'm adding it to the Placeholder because I don't know exactly where the table will be located on the page until runtime. Before the form control table is added to the Placeholder, I'm adding a whole bunch of tables to the Placeholder. This is a flowchart program and I have multiple action boxes...
1
1299
by: Bishop | last post by:
I have a page that generates a grid of controls; at the end of each row is an update button that is dynamically created with an associated click event. The grid changes based on the date selected in the calendar control and I populate this grid of controls by calling a routine in the page load event. My dilemma is that the page load event executes before my grid control event during a postback, thus the date that the grid references does...
1
3134
by: CS Wong | last post by:
Hi, I have a page form where form elements are created dynamically using Javascript instead of programatically at the code-behind level. I have problems accessing the dynamically-created elements and would like to seek a solution for this. I had looked through several articles for accessing programatically-created dynamic elements such as: 1)
5
4547
by: | last post by:
I am wondering what the best method of attaching custom Events to custom WebUserControls are. I cannot seem to find the proper terminology to expand my research. Basicallly I have a custom user control that has 2 or 3 events selectionChanged DropDownOpened I would like the user to be able to attach Server Side events for both. I have the client side implementation worked out. I just need to find a proper way to to get everything...
7
2344
by: mavigozler | last post by:
IE7 does not appear to set an event on contained text inside SPAN elements whose 'onclick', 'onmouseover', and 'onmouseout' events, defying the HTML recommendation. Firefox appears to conform. Is that so?
2
1651
by: Nathan Sokalski | last post by:
I have LinkButtons that are dynamically created in one of the PostBack events. They must be created in the PostBack event because one of the variables required to determine which ones to create comes from the event arguments. Because the LinkButtons are not created in the Init event, they will not exist when I click them to perform a postback. How do I handle the events for these LinkButtons? I appreciate any help you can give. Thanks. --...
0
9522
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
10111
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...
0
9948
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
0
9765
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
8770
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...
1
7327
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6603
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();...
3
3446
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2738
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.