Question:
How to replace multiple images with onclick in HTML?
Jeanne V
2012-06-05 21:56:08 UTC
So i made it that when i click on an image, it changes and then it is changed back to the original image when clicked again. I wanna try to do this with another image on the same page but it seems to only work once with the code i am using.
could anyone help me change to different images each time with clicking on the image? heres my code:









Click to turn on/off the light






also i am using notepad++ to code all this
Three answers:
2012-06-05 22:17:04 UTC
Change onclick="changeimage()" to onclick="changeimage(this)" then you can add multiple img tags in the html and the action will be on that specific image.



i.e.







In your function:

function changeimage(elm)

{

if (cc==0)

{

cc=1;

elm.src="…

}

else

{

cc=0;

elm.src="…

}
2012-06-06 05:37:22 UTC
All right Big code change to your changeImage function, but once you do, you can add as many images as you'd like and do this. Never have to update the function or add another for this again, really.



function changeImage(imgID) {

i = document.getElementById(imgID);

state = i.getAttribute("state");

img1 = i.getAttribute("img1");

img2 = i.getAttribute("img2");



switch(state){

case "1":

i.src = src2;

i.setAttribute("state", "2");

break;



case "2":

i.src = src1;

i.setAttribute("state", "1");

}



// End function to change images



Now, there's that. It changes three things.. all in the img tag.

imgID is the id attribute in the image.

img1="imageSrc.jpg" // The src of the first image. Likely the same as the original src.

img2="imageSrc2.gif" // The alternate image src. Changed from the default.

state="1" // Always "1" at first, in the original code. This keeps track of which image is showing where.



Now, in the body, the tags for images look like this:







Hopefully that solves it! Good luck, and you can likely copy/paste the function I wrote there.

Should work for you.



See the working example at: http://test-drive.websby.tc/image-switcher-using-javascript/
?
2012-06-06 05:12:33 UTC
Do not use OnClick event rather use OnHover or OnMouseOver & OnMouseOut events.



http://acmeous.blogspot.in/2008/07/simplest-way-to-change-images-on-mouse.html



Or Use CSS

http://kyleschaeffer.com/best-practices/pure-css-image-hover/


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...