473,405 Members | 2,373 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,405 software developers and data experts.

dynamically assign event to element

How can I dynamically assign an event to an element?

I have tried :
(myelement is a text input)

document.getElementById('myelement').onKeyUp =
"myfnc(param1,param2,param3)";

document.getElementById('myelement')[onKeyUp] = new
Function("myfnc(param1,param2,param3)");

document.getElementById('myelement').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 12531


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


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

--

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

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

I have tried :
(myelement is a text input)

document.getElementById('myelement').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,param2,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.getElementById('myelement')[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.getElementById('myelement')['onkeyup']

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

document.getElementById('myelement').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,param2,param3);
}

....
elementRef.onkeyup = 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.onkeyup = myfnc;

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

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

- or -

var funcRef = new Function("myfnc(param1,param2,param3)");
elementRef.onkeyup = 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.onkeyup = function(myfnc(param1,param2,param3););

- or -

var funcRef = function(myfnc(param1,param2,param3););
elementRef.onkeyup = funcRef;

The function expression - function(myfnc(param1,param2,param3);) - 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('return;')) == '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*****@microsoft.com> writes:
How can I dynamically assign an event to an element?

I have tried :
(myelement is a text input)

document.getElementById('myelement').onKeyUp = .... None of these work. :(


The last two would work, if you had "onkeyup" in lowercase.
Try
document.getElementById('myelement').onkeyup = new
Function("myfnc(param1,param2,param3)");
or
document.getElementById('myelement').onkeyup =
function(){myfnc(param1,param2,param3);};

In IE, you can also use attachEvent:

document.getElementById('myelement').attachEvent(
"onkeyup",
function(){myfnc(param1,param2,param3);}
);

In W3C DOM compliant browsers you can use addEventListener:

document.getElementById('myelement').addEventListe ner(
"keyup",
function(){myfnc(param1,param2,param3);},
false
);

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

document.getElementById('myelement').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
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...
2
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...
4
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:...
0
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...
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...
1
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...
4
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...
9
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...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
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
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
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,...
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
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...
0
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,...

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.