SitePoint Sponsor

User Tag List

Results 1 to 3 of 3
  1. #1
    SitePoint Guru
    Join Date
    Nov 2005
    Location
    Midwest
    Posts
    777
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Change Image Source Using Obj

    Hello

    This should be an easy one but I am having a little issue.

    I can change the image source using the document.getElementById but I thought I should also be able to change it passing the object itself. In the below example, I have commented out the document.getElementById and it works but I was trying to also get it to work passing the obj but it is not working and it is not throwing a JavaScript error. What I have done incorrect here?

    Code:
    <html>
    <head>
    <script language="JavaScript">
    function changeImage( obj, img )
    {
       obj.src = img;
       //document.getElementById( "home" ).src = img;
    }
    </script>
    </head>
    <body>
    <table>
       <tr>
          <td>
    	     <a onMouseOver="changeImage(this, 'home_on.jpg');" onMouseOut="changeImage(this, 'home.jpg');";><img src="home.jpg" name="home" id="home" /></a>
          </td>
       </tr>
    </table>
    </body>
    </html>

  2. #2
    Unobtrusively zen silver trophybronze trophy
    paul_wilkins's Avatar
    Join Date
    Jan 2007
    Location
    Christchurch, New Zealand
    Posts
    14,729
    Mentioned
    104 Post(s)
    Tagged
    4 Thread(s)
    When you pass the this keyword, the reference is to the element that the event occured on, in this case the anchor object.

    Changing the src of the anchor object doesn't do much. Move the events to the image itself and it will work fine.

    There is a much better way to do rollover images. Check out this screencast on making a three-state menu using css sprites.
    http://css-tricks.com/videos/css-tricks-video-7.php
    Programming Group Advisor
    Reference: JavaScript, Quirksmode Validate: HTML Validation, JSLint
    Car is to Carpet as Java is to JavaScript

  3. #3
    SitePoint Guru
    Join Date
    Nov 2005
    Location
    Midwest
    Posts
    777
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thank you for both tips… that does clean up the code.

    Here is how I did it.

    Code HTML4Strict:
    <html>
    <head>
    <link rel="stylesheet" type="text/css" href="menu.css" />
    </head>
    <body>
    <table>
       <tr>
          <td class="menuHome">
    	     <a href="#";></a>
    	  </td>
       </tr>
    </table>
    </body>
    </html>

    Code CSS:
    .menuHome a
    {
    	display: block;
    	width: 69px;
    	height: 34px; 
    	background: transparent url( 'home_both.jpg' ) no-repeat;
    }
     
    .menuHome a:hover
    {
    	background-position: -69px 0;
    }


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •