faqts : Computers : Programming : Languages : JavaScript : Event handling

+ Search
Add Entry AlertManage Folder Edit Entry Add page to http://del.icio.us/
Did You Find This Entry Useful?

58 of 88 people (66%) answered Yes
Recently 4 of 10 people (40%) answered Yes

Entry

How do I attach an event handler with js?

Feb 12th, 2000 08:38
Martin Honnen,


With HTML you attach event handlers to HTML elements by providing an 
HTML attribute whose string value is some js code e.g.
  <IMG NAME="anImage" SRC="whatever.gif" ONLOAD="alert('loaded');">
This is equivalent to defining a JavaScript event handler function
  function loadHandler (evt) {
    alert('loaded'); 
  }
and assiging the function object
  loadHandler
to the IMG's event handler property:
  document.anImage.onload = loadHandler;

Common errors here are instead of assigning the function object as 
above 
1) to call the handler function:
  document.anImage.onload = loadHandler()
which is wrong as it simply calls loadHandler and assigns its result to
  document.anImage.onload
not making
  document.anImage.onload
a function but making it undefined
2) to simply assign a string
  document.anImage.onload = "alert('loaded')"
which doesn't make 
  document.anImage.onload
a function which can be triggered but simply a string.