Give the images you create dynamically a class, using their CssClass property:
// Dynamically create the image control in code behind
Image image = new Image();
Image.CssClass = "change-on-hover";
Image.ImageUrl = "image.jpg"; // Of course, this is dynamic from the database
// Save the alternative image URL in a data-attribute
Image.Attributes["data-alternate-image"] = "image-over.jpg";
parent.Controls.Add(image);
This will render each image like this:
<img src="image.jpg" class="change-on-hover"
data-alternative-image="image-over.jpg" />
Then in jQuery, you can find all the images with this class to bind the behavior:
$("img.change-on-hover")
.on("mouseover", function(e) {
// Save original src (image.jpg)
$(this).data("original-image") = this.src;
// Change src to alternative (image-over.jpg)
this.src = $(this).data("data-alternate-image");
})
.on("mouseout", function(e) {
// Change src back to original
this.src = $(this).data("original-image");
});
The data-alternative-image attribute is a nice way to store some information inside the image tag from code behind, that you can then later read in your JavaScript event handler. You can make your own data-attributes any way you like.
Some more info about the data-attribute: http://ejohn.org/blog/html-5-data-attributes/
img:hover { background-image: 'other.png' }