Page 1 of 1

Javascript Image Swap

Posted: Sat Jan 30, 2010 9:43 pm
by stuartshields
I have a question, I have 2 images, lets say one is the colour Black and the other is the Colour Red. Black is the default image, when they click on the black image it turns red.

Mind you there is going to be 5 lots of this with different colours, and it will randomly generate the images in different positions.

Just wondering the best way to do this. I know I need to have loop it inside a function. Any hits or real world practices would be nice.

Re: Javascript Image Swap

Posted: Sun Jan 31, 2010 2:12 pm
by califdon
The HTML <img> element has an attribute "src=" that can be set with Javascript. Generally it will look something like this:

Code: Select all

...
<head>
  <script type='text/javascript'>
    function changeimg()  {
      getElementById('myimg').src='red.jpg';
    }
  </script>
</head>
<body>
...
  <input type='button' value='Click to change image' onClick='changeimg();'>
...
  <img id='myimg' src='black.jpg'>
...

Re: Javascript Image Swap

Posted: Sun Jan 31, 2010 3:26 pm
by stuartshields
Califdon, thanks it's along the lines of what I need... Although no input required it has to be on the image. Thank you very much :)

Re: Javascript Image Swap

Posted: Sun Jan 31, 2010 3:59 pm
by califdon
Oh, right. That was just an example. You'll need to work out the logic, looping, etc., but the changing of the image is done by changing the "src=" attribute.