473,725 Members | 1,942 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

dynamically assign event to element

How can I dynamically assign an event to an element?

I have tried :
(myelement is a text input)

document.getEle mentById('myele ment').onKeyUp =
"myfnc(param1,p aram2,param3)";

document.getEle mentById('myele ment')[onKeyUp] = new
Function("myfnc (param1,param2, param3)");

document.getEle mentById('myele ment').onKeyUp = new
Function("myfnc (param1,param2, param3)");
None of these work. :(
Can someone please show my how to do this? (if the syntax is different for
IE and NS, please show me both)

Thanks!
-Eric
Jul 20 '05 #1
4 12577


Eric wrote:
How can I dynamically assign an event to an element?


elementObject.o nmouseover = function (evt) {
// your code goes here
};

--

Martin Honnen
http://JavaScript.FAQTs.com/

Jul 20 '05 #2
"Eric" <so*****@micros oft.com> wrote in message
news:4K******** **************@ bgtnsc05-news.ops.worldn et.att.net...
How can I dynamically assign an event to an element?

I have tried :
(myelement is a text input)

document.getEle mentById('myele ment').onKeyUp =
The event handling properties of DOM elements are normally exclusively
lower case so "onKeyUp" should be "onkeyup". The only context in which
you have the freedom to use mixed case is in the names of HTML event
handling attributes, because HTML is case insensitive. There are some
browsers that will tolerate mixed case event handling property names but
they will still be happy with the all lower case versions and the
browsers that only recognise the all lower case names require there use.
"myfnc(param1,p aram2,param3)";
A string is not a function and normally assigning a string to an event
handling property will not result in the automatic creation of a
corresponding function object. Again, there are some browsers that will
use an assigned string value to internally create a function object, but
not many so it is better to always assign function objects to event
handling properties.
document.getEle mentById('myele ment')[onKeyUp] = new
Square bracket property accessors take an expression that is resolved to
a string value and then use that string value as the property name. In
the above - [onKeyUp] - is not a string literal and - onKeyUp - will be
interpreted as an identifier (usually for a local or global variable).
Baring in mind that the property name should be all lowercase, that
property accessor probably should have been:-

document.getEle mentById('myele ment')['onkeyup']

<URL: http://www.jibbering.com/faq/#FAQ4_39 >
Function("myfnc (param1,param2, param3)");

document.getEle mentById('myele ment').onKeyUp = new
Function("myfnc (param1,param2, param3)");
None of these work. :(

<snip>

The last should have worked if the property name was all lower case.

There are three approaches to assigning functions to event handling
properties of DOM elements.
1. Assigning a reference to a function:-

function customOnKeyUp() {
myfnc(param1,pa ram2,param3);
}

....
elementRef.onke yup = customOnKeyUp;
....

Note that the function name is used without parentheses, as that would
call the function. The function name alone is a (usually) global
property/variable that holds a reference to a corresponding function
object and the above assignment copies the reference to that function
object to the onkeyup property of the element so that it too refers to
the function object.

However, in the example above - myfnc - would be a global function and
param1,param2 and param3 would also be global variables else none of
them could be usefully resolved, In which case - myfnc - does not need
parameters as it can be written to reference the global variables
directly and so it would be possible to assign a reference to - myfnc -
directly to the event handling attribute - elementRef.onke yup = myfnc;

2. Dynamically creating a function object using the Function constructor
and assigning a reference to it to the event handling property:-

elementRef.onke yup = new Function("myfnc (param1,param2, param3)");

- or -

var funcRef = new Function("myfnc (param1,param2, param3)");
elementRef.onke yup = funcRef;

In the second example the reference to the newly created function object
is held in a local variable - funcRef - and then assigned to the event
handling property. That would allow the same function object reference
to be assigned to the properties of numerous DOM elements rather than
creating a unique function object for each DOM element.

3. Assigning a function expression to the event handling property:-

elementRef.onke yup = function(myfnc( param1,param2,p aram3););

- or -

var funcRef = function(myfnc( param1,param2,p aram3););
elementRef.onke yup = funcRef;

The function expression - function(myfnc( param1,param2,p aram3);) - is
evaluated as a reference to an anonymous function object and that
reference is assigned to the event handling property of the DOM element
in the first example. In the second example it is assigned to a variable
and can again then be assigned to the appropriate property of multiple
DOM elements.

All three approaches are cross-browser and each has its merits and
drawbacks.

The main reason for using the Function constructor (2) is when the
function body string is itself dynamically constructed at runtime, its
drawback is that there are a (*very*) few browsers[1] that do not
implement the Function constructor due to limited client-side resources
(browsers found on PDAs and cell phones). In principal the presence or
absence of the Function constructor can be tested for, as could the
effectiveness of its use.

if((typeof Function == 'function')&&
(typeof (new Function('retur n;')) == 'function')){
//Function constructor probably OK to use.
}

The function expression option (3) is probably the easiest to write but
its drawback comes form the fact that function expressions are often
(usually) also inner functions and assigning them to properties of DOM
elements can induce the IE memory leak problem because of the closure
formed by the assignment. (lots of ways of avoiding that or negating the
harmful effects.)

It is also possible for the function referenced in the first approach to
be an inner function, producing the same risks as the function
expressions on IE. But usually the function referenced would be defined
as a global function and that problem would not arise.

I suspect that your question really involves assigning an event handling
function _with_ parameter defined at the point of the assignment, but
that is a different question so you will have to say if that is
relevant.

Richard.

[1] I only know of one by name.
Jul 20 '05 #3
"Eric" <so*****@micros oft.com> writes:
How can I dynamically assign an event to an element?

I have tried :
(myelement is a text input)

document.getEle mentById('myele ment').onKeyUp = .... None of these work. :(


The last two would work, if you had "onkeyup" in lowercase.
Try
document.getEle mentById('myele ment').onkeyup = new
Function("myfnc (param1,param2, param3)");
or
document.getEle mentById('myele ment').onkeyup =
function(){myfn c(param1,param2 ,param3);};

In IE, you can also use attachEvent:

document.getEle mentById('myele ment').attachEv ent(
"onkeyup",
function(){myfn c(param1,param2 ,param3);}
);

In W3C DOM compliant browsers you can use addEventListene r:

document.getEle mentById('myele ment').addEvent Listener(
"keyup",
function(){myfn c(param1,param2 ,param3);},
false
);

Good luck.
/L
--
Lasse Reichstein Nielsen - lr*@hotpop.com
DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
'Faith without judgement merely degrades the spirit divine.'
Jul 20 '05 #4
Lasse Reichstein Nielsen wrote:
"Eric" <so*****@micros oft.com> writes:
How can I dynamically assign an event to an element?
I have tried :
(myelement is a text input)

document.getEle mentById('myele ment').onKeyUp =

....
None of these work. :(


The last two would work, if you had "onkeyup" in lowercase.


Only the last one would have worked then, since the operand
of the square bracket property accessor needs to be numeric
(i.e. of type `number') or a string (i.e. of type `string').
The unquoted property identifier would then have been read
as variable reference and thus most certainly have failed.
PointedEars
Jul 20 '05 #5

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

Similar topics

3
12484
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)
2
3645
by: Bill Agee | last post by:
I have a subform called PaymentDetails and would like to dynamically assign the recordsource after the form/subform is opened. The recordsource for Payment Details is "PaymentDetails_qry" which uses a function to filter the Invoice #. The invoiceID is not known until after the form is opened. After the InvoiceID is selected from a dropdown I then want to assign the recordsource ...
4
2565
by: hb | last post by:
Hi, When I add an asp:button (ex: id=btnLog) on home.aspx, I need to create btnLog_Click() event in home.aspx.cs, and also link this event and the button in OnInit() method by adding: this.btnLog.Click +=new System.EventHandler(this.btnLog_Click); Now, I need to generate some asp:button dynamically in an asp:table, and assign the event to all buttons. But in
0
3383
by: cyberbless | last post by:
I would like to dynamically assign a Select Statment to a a SqlDataSource. Problem is the SqlDataSource.Select() Command requires a "dataSourceSelectArgument" as one of its arguments. 1. What if I don't have an argument to give to out our the Select Statement. Or if the arguments are pre-assigned. Take the following lines of code for example. --------------------------------------------------------- SqlDataSource.InsertCommand =...
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...
1
8949
by: chrisdr | last post by:
I found this code in a previous post but I am not able to get this to work for me... I am trying to dynamically change an element's type from textbox to textarea with an event. Actually in my code i'm using a onClick event on a checkbox, but this is the original code exactly the way it was in the previous post... I tried to use it as it is and it errors out... Any input on how to make this code work or any other suggestions on how to accomplish...
4
2201
by: .Net Sports | last post by:
I need to dynamically assign a datalist attribute upon a helper function receiving data from a querystring. If a user picks a certain region, i need the datalist to display its back color, or any of its other objects , as a certain color or css style <HeaderStyle BackColor="<%= ssponcont %>"</HeaderStyle> ....doesnot work as a Parser error renders: Content ('<HeaderStyle
9
2784
by: student4lifer | last post by:
Hello, could someone show me how to make sticky form with dynamically generated form element? for example, if one likes to make the dynamically generated check box (and its name) 'sticky' that retains the value of the previously submitted value. How would one do that? TIA. I was thinking something along this line but not sure it's the right way to accomplish this task
0
8888
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
9401
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
9257
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...
1
9174
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
8096
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
6702
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
6011
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
3221
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
3
2157
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.