devxlogo

Event Handling for Dynamically Added Objects

Event Handling for Dynamically Added Objects

Question:
I have used InsertAdjacentHTML to insert a dynamic number of images onto a page in Internet Explorer 4. Having given the new images a single ID, I can refer to images in the script using I[0], I[1], etc., and alter properties for each image. However, events seem to be ignored for all of these images. Can you tell me why this is happening in IE and how I can create a cross-browser solution?

Answer:
This problem may be caused by the event handler or the language that you’re using. VBScript seems to have problems with multiple elements with a common name, though JavaScript works fine. With Internet Explorer, you still use the base name (without indices) to catch the event, using the alternate syntax:

where testImage is the name of the group of images being created. The routine GetImageIndex is defined in the HTML sample below, showing how you can retrieve the index of the image that you’re currently clicking on or mousing over. This solution is IE4+ specific, although the Netscape test is similar: change the output(id,whichText) handler to handle the document.id.document.write() call instead of insertAdjacentHTML().

	Multi-Image Test

See also  Why ChatGPT Is So Important Today
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist