473,561 Members | 3,259 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 12551


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
12471
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. ...
2
3637
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...
4
2555
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...
0
3374
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...
7
2518
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....
1
8915
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...
4
2189
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...
9
2770
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...
0
7570
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 effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language...
1
7618
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...
0
7930
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...
0
6210
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...
0
3617
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3600
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2068
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
1
1181
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
896
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...

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.