Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change image on hover using asp:imagebutton and CSS?

Tags:

.net

css

asp.net

I have the following code but it doesnt seem to work:

<td align="center" style="padding-bottom:52.5px">
<asp:ImageButton CssClass="RightArrow" ID="Image2" runat="server"     ImageUrl="/_layouts/Right_GrayArrow.png"/>
</td>

And a CSS class to change image on hover:

.RightArrow:hover
{
background-image: url('/_Layouts/Right_GreenArrow.png') !important;
}

Please advise. Thanks

like image 629
user1266515 Avatar asked Jun 18 '12 15:06

user1266515


2 Answers

I prefer this way:

<asp:ImageButton CssClass="RightArrow" ID="Image2" runat="server" ImageUrl="/_layouts/Right_GrayArrow.png" onmouseover="this.src='/_layouts/Right_GreenArrow.png'" onmouseout="this.src='/_layouts/Right_GrayArrow.png'"/>

bye

like image 80
Fabrizio Avatar answered Sep 23 '22 01:09

Fabrizio


An ImageButton controls renders as a <input type="image" /> element with the ImageUrl property becoming the src attribute like:

<input type="image" src="/_layouts/Right_GrayArrow.png" />

Therefore you are applying a background image to this, which you cannot see as the src image is being overlayed on top of it.

You have 2 choices:


1) Change the ImageButton to use a background image:

.RightArrow
{
  width: /* width of image */
  height: /* height of image */
  background-image:url('/_layouts/Right_GrayArrow.png');
}
.RightArrow:hover
{
  background-image: url('/_Layouts/Right_GreenArrow.png');
}

If you are going to use this method though, I would recommend using an <asp:Button /> instead. It seems pointless using an <asp:ImageButton /> if you're not even making use of the src attribute.


2) Use jQuery to change the image on hover:

$(".RightArrow").hover(function(){
   $(this).attr("src", "/_Layouts/Right_GreenArrow.png");
},
function(){
   $(this).attr("src", "/_Layouts/Right_GrayArrow.png");
});

Worth noting this will only work with javascript enabled, and you must include the jQuery library.

like image 25
Curtis Avatar answered Sep 27 '22 01:09

Curtis