Click here to Skip to main content
15,889,842 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,

I tried modifing the java script part of the below codes as

Original code:-

HTML
<html>
<img id="myImage" >
<script>


JavaScript
function changeImage() {
    var image = document.getElementById('myImage');
    if (image.src.match("bulbon")) {
        image.src = "pic_bulboff.gif";
    } else {
        image.src = "pic_bulbon.gif";
    }
}
</script>
</html>

Modified java script :-
function changeImage() {
    var image = document.getElementById('myImage');
    if (image.src == "pic_bulbon.gif") {
        image.src = "pic_bulboff.gif";
    } else {
        image.src = "pic_bulbon.gif";
    }
}

When this original code is executed the bulb will both on and off as many as times we click.
But when this modified code is executed the bulb will just on and it will not get off
Both are if loops but why is this happening? Kindly help me understand.
Posted
Updated 22-Nov-14 1:32am
v2
Comments
Afzaal Ahmad Zeeshan 22-Nov-14 7:33am    
if is not a loop.

Can you create a fiddle for that? This doesn't seem to make any sense.
Richard MacCutchan 22-Nov-14 7:57am    
Add some extra display code into the function to see exactly what values are in each variable, and what is the result of the if statement.

1 solution

The better way to match image src attribute is :

JavaScript
function changeImage() {
    var image = document.getElementById('myImage');
    
    if (image.getAttribute('src')=="pic_bulbon.gif") {
        image.src = "pic_bulboff.gif";
    } else {
         
        image.src = "pic_bulbon.gif";
    }
}


This works.
 
Share this answer
 
Comments
Ishpreet Kaur 22-Nov-14 13:56pm    
The modified function you written will get on and then doesn't get off. When first time, you click on image, then else part work, and when you again click, then it doesn't go to if part, that's why, it does not get off on second time click.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900