Search code examples
javascriptjqueryonmouseoveronmouseout

Javascript image change


Javascript is being used to make a neat log-out button. It works almost perfectly except I cannot figure out how to attach a line to the 'span' so it also edits the image because the code uses a self variable. How can I get the image to be used in script attached to the span in the link so the image changes regardless if I am hovering over the link or the image. I have tried to use a few solutions but nothing either worked the way I wanted it to or not at all. JQuery is fine for a solution as well. I am very ignorant as far as Javascript/JQuery goes as most of my coding so far is PHP/CSS.

<a href="#logout">
<span>Logout</span>
<img src="images/logout.png" 
  onmouseover="this.src='images/logout_hover.png'" 
  onmouseout="this.src='images/logout.png'" />
</a>

Solution

  • Since events propagate, this should work:

    <a id="login_link" href="#logout" onmouseover="document.getElementById('login_image').src='images/logout_hover.png'" onmouseout="document.getElementById('login_image').src='images/logout.png'">
        <span>Logout</span>
        <img src="images/logout.png" id="login_image" />
    </a>
    

    But as 2pha mentioned, using simple CSS is a lot better:

    #login_link span#logo_image {
        display: inline-block;
        width: 100px;
        height: 30px;
        background: transparent url(images/logout.png) top left no-repeat;
    }
    #login_link:hover span#logo_image {
        background-image: url(images/logout_hover.png);
    }
    

    Or better yet, merge the 2 images and use the new image as a sprite, so they will preload together:

    #login_link span#logo_image {
        display: inline-block;
        width: 100px;
        height: 30px;
        background: transparent url(images/logout.png) top left no-repeat;
    }
    #login_link:hover span#logo_image {
        background-position: bottom left;
    }