JavaScript Events Not Firing

September 21, 2008 at 3:45 PMBen

It's important to realize a JavaScript event is not guaranteed to fire.  The events I have in mind are events such as onmouseout and onmouseover.  I'm sure there are many other events that also may not fire depending on the circumstances at the time the events would normally fire.  If the element is right up against the edge of the browser viewport when the mouse moves away from the element and out of the browser, or if the browser or computer is busy processing something else at the time the event would be expected to occur, it may just not happen.

While working with jQuery recently I created a rollover image with the hover() function to show a different image when the mouse rolls over the image.  The particular piece of code was:

oImgBtn.hover(
  function(){ this.src = this.src.replace('.gif','_over.gif'); },
  function(){ this.src = this.src.replace('_over',''); }
);


This code works good assuming your rollover image has the same filename as the original image with "_over" at the end of the filename.  The problem occurred one time while testing the page.  I noticed the image replacement was not occurring and I was getting some ugly flickering when hovering over the image.  Fortunately, I had Firebug already turned on and checking the Net tab showed a red item indicating a 404 error.  The file that the browser was getting a 404 on had this filename:

myImage_over_over.gif

Apparently, one of the previous times I had rolled over the image, for whatever reason the onmouseout event didn't fire leaving the images source as myImage_over.gif (the rollover image).  The next time I rolled over the image, the onmouseover event fired changing the image's source from myImage_over.gif to myImage_over_over.gif.  Not good!  A very easy and effective solution in this case was to make sure a preexisting "_over" in the image source was removed prior to adding it back in the onmouseover event handler.

oImgBtn.hover(
  function(){ this.src = this.src.replace('_over', '').replace('.gif','_over.gif'); },
  function(){ this.src = this.src.replace('_over',''); }
);


This is a much more robust method of making sure things don't fall apart in the rare event a JavaScript event doesn't fire.  Although rollover images are not usually critical to a page's functionality, it's still a bad experience to the end user if they see things flickering that shouldn't be flickering.  This also makes you realize that for any client side code, it's important to not assume events will always fire and be sure your code is defensively designed so it can recover from unexpected situations.

Posted in: Development

Tags: ,

Comments are closed