File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes HTML, CSS and JavaScript and the fly likes setAttribute for img event handler Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "setAttribute for img event handler" Watch "setAttribute for img event handler" New topic

setAttribute for img event handler

Richard Robbins
Ranch Hand

Joined: Mar 07, 2001
Posts: 66
I am dynamically creating an image in an HTML document using "nextImage = document.createElement( "img" )", and I would like to be able to add event handlers that apply to this image (onclick, onmouseover, onmouseout). Whenever I add the code: "nextImage.setAttribute( "onmouseover", "swapImage()" )", nothing happens when I mouse over the image. Is is possible to add an event handler to a dynamically created element using setAttribute or any other DOM method?
As a note, I tried using an anchor as the image's parent, and that allowed me to use setAttribute( "href", "javascript:...") as a substitute for onclick, but I don't want the image to be the child of an anchor, and I still have the problem of rotating images for onmouseover and onmouseout events. Is there an expert out there who is more familiar with this than I am and can help out?

Richard Robbins is one of the founders of, a resource for free website templates and Photoshop tutorials. He also consults for an online boutique selling baptism dresses and christening gowns.
I agree. Here's the link:
subject: setAttribute for img event handler
It's not a secret anymore!