Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
176
rated 0 times [  182] [ 6]  / answers: 1 / hits: 25267  / 12 Years ago, tue, june 26, 2012, 12:00:00

I have three images: the first is a light switch, the second is an off light bulb and the third is an on light bulb. When a user clicks on the light switch image, I would like it to change the off light bulb image into the on light bulb image. Is this possible?



These are the images:



switch off on



Javascript:



img2=new Image();
img2.src=images/RCS/lightbul2-250.gif;
img3=new Image();
img3.src=images/RCS/lightbuld1.gif;

function changeImage() {
document.getElementById('myImage').src=img2.src;
}
function changeImage2() {
document.getElementById('myImage').src=img3.src;
}


HTML:



<img id=myImage onmouseover=changeImage() onmouseout=changeImage2() border=0 width=250 height=141 src=images/RCS/lightbulb1-100.gif>

More From » html

 Answers
61

You can also achieve this without JQuery by using if/else statements.



HTML Markup:



<a href=# onClick=changeImage()><img src=lightSwitch.jpg></a>
<img id=myImage src=lightOff.jpg>


Javascript:



function changeImage() {
if(document.getElementById('myImage').src == 'lightOff.jpg') {
document.getElementById('myImage').src = 'lightOn.jpg';
} else if(document.getElementById('myImage').src == 'lightOn.jpg') {
document.getElementById('myImage').src = 'lightOff.jpg';
}
}


JS Fiddle Example


[#84654] Monday, June 25, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
janettejordynm

Total Points: 550
Total Questions: 94
Total Answers: 98

Location: Senegal
Member since Fri, Aug 21, 2020
4 Years ago
janettejordynm questions
Tue, Nov 24, 20, 00:00, 4 Years ago
Sat, May 23, 20, 00:00, 4 Years ago
Mon, Apr 6, 20, 00:00, 4 Years ago
Tue, Feb 18, 20, 00:00, 4 Years ago
;