CSS Sprite Hover Effect

1. Create a composite resource definition that represents a CSS Sprite.

WebControls
    <xpedite:CompositeResource runat="server" Type="Png" ReferenceName="sample">
      <xpedite:Resource Url="/Images/C.png" ReferenceName="c" />
      <xpedite:Resource Url="/Images/Dash.png" ReferenceName="dash" />
      <xpedite:Resource Url="/Images/E.png" ReferenceName="e" />
      <xpedite:Resource Url="/Images/I.png" ReferenceName="i" />
      <xpedite:Resource Url="/Images/P.png" ReferenceName="p" />
      <xpedite:Resource Url="/Images/R.png" ReferenceName="r" />
      <xpedite:Resource Url="/Images/S.png" ReferenceName="s" />
      <xpedite:Resource Url="/Images/T.png" ReferenceName="t" />
    </xpedite:CompositeResource>

MVC HtmlHelper
<asp:Content ID="HeadContentPlaceHolder" ContentPlaceHolderID="head" runat="server">
  <%= Html.CompositeImageResource(
        "sample",
        new [] {
          new Resource("c", "/Images/C.png"),          
          new Resource("s", "/Images/S.png"),
          new Resource("dash", "/Images/Dash.png"),
          new Resource("p", "/Images/P.png"),
          new Resource("r", "/Images/R.png"),
          new Resource("i", "/Images/I.png"),
          new Resource("t", "/Images/T.png"),
          new Resource("e", "/Images/E.png")
        })%>
</asp:Content>

2. Reference an image within the composite resource definition (note: use of an ID selector is recommended).

WebControls
    <xpedite:Spriterunat="server"  ID="mySpriteReference" SpriteName="sample" ImageName="c" />

MVC HtmlHelper
    <%= Html.CssSprite("sample", "c", "The letter C", "mySpriteReference")%>

3. Bind the hover event on document ready (or whever is desired).

      $.fn.replaceClass = function (oldClass, newClass) {
        var $this = $(this);

        if ($this.hasClass(oldClass)) {
          $this.removeClass(oldClass);
        }

        if (!$this.hasClass(oldClass)) {
          $this.addClass(newClass);
        }
      };

      $(document).ready(function () {
        $("#mySpriteReference").hover(
          function (e) { $(this).replaceClass("c", "dash"); },
          function (e) { $(this).replaceClass("dash", "c"); }
        );
      });

Last edited Oct 31, 2010 at 4:17 PM by CBaxter, version 3

Comments

No comments yet.