dynamically assign event to element

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Eric

    #1

    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


  • Martin Honnen

    #2
    Re: dynamically assign event to element



    Eric wrote:
    [color=blue]
    > How can I dynamically assign an event to an element?[/color]

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

    --

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

    Comment

    • Richard Cornford

      #3
      Re: dynamically assign event to element

      "Eric" <someone@micros oft.com> wrote in message
      news:4KZFb.2312 59$Ec1.8190942@ bgtnsc05-news.ops.worldn et.att.net...[color=blue]
      > How can I dynamically assign an event to an element?
      >
      > I have tried :
      > (myelement is a text input)
      >
      > document.getEle mentById('myele ment').onKeyUp =[/color]

      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.
      [color=blue]
      > "myfnc(param1,p aram2,param3)";[/color]

      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.
      [color=blue]
      > document.getEle mentById('myele ment')[onKeyUp] = new[/color]

      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 >
      [color=blue]
      > Function("myfnc (param1,param2, param3)");
      >
      > document.getEle mentById('myele ment').onKeyUp = new
      > Function("myfnc (param1,param2, param3)");
      >
      >
      > None of these work. :([/color]
      <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.


      Comment

      • Lasse Reichstein Nielsen

        #4
        Re: dynamically assign event to element

        "Eric" <someone@micros oft.com> writes:
        [color=blue]
        > How can I dynamically assign an event to an element?
        >
        > I have tried :
        > (myelement is a text input)
        >
        > document.getEle mentById('myele ment').onKeyUp =[/color]
        ....[color=blue]
        > None of these work. :([/color]

        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 - lrn@hotpop.com
        DHTML Death Colors: <URL:http://www.infimum.dk/HTML/rasterTriangleD OM.html>
        'Faith without judgement merely degrades the spirit divine.'

        Comment

        • Thomas 'PointedEars' Lahn

          #5
          Re: dynamically assign event to element

          Lasse Reichstein Nielsen wrote:
          [color=blue]
          > "Eric" <someone@micros oft.com> writes:[color=green]
          >> How can I dynamically assign an event to an element?
          >> I have tried :
          >> (myelement is a text input)
          >>
          >> document.getEle mentById('myele ment').onKeyUp =[/color]
          > ....[color=green]
          >> None of these work. :([/color]
          >
          > The last two would work, if you had "onkeyup" in lowercase.[/color]

          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

          Comment

          Working...