Javascript Image Swap

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
stuartshields
Forum Newbie
Posts: 10
Joined: Sat Jan 30, 2010 8:59 pm
Location: Toowoomba

Javascript Image Swap

Post 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.
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Javascript Image Swap

Post 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'>
...
stuartshields
Forum Newbie
Posts: 10
Joined: Sat Jan 30, 2010 8:59 pm
Location: Toowoomba

Re: Javascript Image Swap

Post 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 :)
User avatar
califdon
Jack of Zircons
Posts: 4484
Joined: Thu Nov 09, 2006 8:30 pm
Location: California, USA

Re: Javascript Image Swap

Post 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.
Post Reply