dynamically assign event to element

Discussion in 'Javascript' started by Eric, Dec 23, 2003.

  1. Eric

    Eric Guest

    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
    Eric, Dec 23, 2003
    #1
    1. Advertising

  2. 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/
    Martin Honnen, Dec 23, 2003
    #2
    1. Advertising

  3. "Eric" <> wrote in message
    news:4KZFb.231259$...
    > 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.
    Richard Cornford, Dec 23, 2003
    #3
  4. "Eric" <> 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').addEventListener(
    "keyup",
    function(){myfnc(param1,param2,param3);},
    false
    );

    Good luck.
    /L
    --
    Lasse Reichstein Nielsen -
    DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleDOM.html>
    'Faith without judgement merely degrades the spirit divine.'
    Lasse Reichstein Nielsen, Dec 23, 2003
    #4
  5. Lasse Reichstein Nielsen wrote:

    > "Eric" <> 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
    Thomas 'PointedEars' Lahn, Dec 27, 2003
    #5
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. hb
    Replies:
    4
    Views:
    15,119
  2. HANM
    Replies:
    2
    Views:
    709
    Joseph Kesselman
    Jan 29, 2008
  3. Adi
    Replies:
    2
    Views:
    191
  4. N. Demos
    Replies:
    0
    Views:
    121
    N. Demos
    Feb 24, 2005
  5. N. Demos
    Replies:
    3
    Views:
    182
    N. Demos
    Feb 28, 2005
Loading...

Share This Page