www.webdeveloper.com
Results 1 to 2 of 2

Thread: addEventListener issue

  1. #1
    Join Date
    Oct 2011
    Posts
    1

    addEventListener issue

    I'm trying to add an event handler for to my body, and for some reason which I can't figure out, it only works on Google Chrome. I wouldn't expect it to work in IE, but am wondering why it's not working in Firefox.

    Here's the relevant parts of the code:

    Javascript (in an external file)
    Code:
    var body = document.body;
    body.addEventListener("load", Foo(), false);
    	
    function Foo(){	
    	addEventListener(document.getElementsByName("start"),"click", alert("hello"), false);
    }
    HTML

    Code:
    <html>
    	<head>
    		<title>BREAKOUT!</title>
    		<script src="breakout.js" type="text/Javascript" >
    		</script>
    		<LINK REL="stylesheet" HREF="breakout.css" TYPE="text/css">
    	</head>
    	
    	<body id="body">
    <!-- etc.... -->

  2. #2
    Join Date
    Aug 2007
    Posts
    3,767
    Well, it shouldn't really work at all! Foo() is the return value of the function, in this case nothing. What you actually want is the function, so you just use Foo without the brackets (like #'Foo if you've ever studied Lisp).
    Code:
    var body = document.body;
    body.addEventListener("load", Foo, false);
    	
    function Foo(){	
    	addEventListener(document.getElementsByName("start"),"click", function() {alert("hello");}, false);
    }
    The anonymous function is for the same reason, equivalent to lambda in Lisp.

    As a matter of interest, John McCarthy who created Lisp died recently, and Lisp and JavaScript share many similarities.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
HTML5 Development Center



Recent Articles