0

I've created a table in my ASP.NET (C#,VS2010) web app whose rows and cells should be created dynamically (read from DB), I have an image in each row which is being created dynamically (in codebehind file), how can I change its image (display a hover) with mouse over? it is easy using a small JavaScript function for statically created controls, but how can it be done for dynamically created controls? can I use inline JS functions? how should I implement it?

thanks

3
  • 1
    use CSS. Don't abuse JavaScript Commented Jan 6, 2012 at 12:15
  • how can I do it with CSS? can you give me a tip please? Commented Jan 6, 2012 at 12:24
  • 1
    img:hover { background-image: 'other.png' } Commented Jan 6, 2012 at 12:27

1 Answer 1

2

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/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.