Cross browser attach event function and firefox events

Discussion in 'JavaScript' started by acl123, Mar 1, 2007.

  1. #1
    Hi,
    I am trying to work out how to access the event object in firefox under two conditions -
    1) Attaching event handlers in javascript, not html.
    2) The event handler requires parameters in addition to the event object.

    Here is an HTML page that demonstrates the problem. Notice that it works in IE but not firefox.

    
    
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
    <html>
    <head>
    <title>My page</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
    </head>
    <body>
    
    <form action="">
    
    <p><input id="testBox" type="text" /></p>
    
    </form>
    
    <script type="text/javascript">
    
    function XBrowserAddHandler(target,eventName,handlerName)
    {
        if ( target.addEventListener )
          target.addEventListener(eventName, handlerName, false);
        else if ( target.attachEvent )
          target.attachEvent("on" + eventName, handlerName);
        else
          target["on" + eventName] = handlerName;
    }
    
    var y = 3;
    
    var txtTestBox = document.getElementById('testBox');
    
    XBrowserAddHandler(txtTestBox, 'keyup', function() { myFunctionRef(y) });
    
    var myFunctionRef = function myFunction(x, e)
    {
        var keyCode;
    
        if (!e && window.event)
            e = window.event;
    
        if (e)
            keyCode = (window.Event) ? e.which : e.keyCode;
    
       alert('You pressed: ' + keyCode + '. Event object is :' + e + '. x is: ' + x);
    }
    </script>
    
    </body>
    </html>
    
    Code (markup):
     
    acl123, Mar 1, 2007 IP
  2. Aragorn

    Aragorn Peon

    Messages:
    1,491
    Likes Received:
    72
    Best Answers:
    1
    Trophy Points:
    0
    #2
    I didn't understand your first condition. Can you give more details?

    Regarding the second condition, change line no. 31 to
    
    XBrowserAddHandler(txtTestBox, 'keyup', function(e) { myFunctionRef(y, e) });
    
    Code (markup):
     
    Aragorn, Mar 2, 2007 IP
  3. acl123

    acl123 Peon

    Messages:
    2
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    0
    #3
    Great thanks for that, it works!
     
    acl123, Mar 4, 2007 IP