5

I want to toggle the image using if-else but it didn't work, can someone please explain what is wrong with the code.

<img src="img/somepic.jpg" id="pic"><br/>

<a href="javascript:toggleImg()">Toggle Image</a>

<script>

function toggleImg(){
    var img = document.getElementById('pic');

    var checkForVisible = img.style.visibility == "visible";

    if(checkForVisible == "visible"){
        img.style.visibility = "hidden";
    }
    else{
        img.style.visibility = "visible";
    }

}

</script>

I tried using "ternary operator"

img.style.visibility = checkForVisible ? "hidden" : "visible";

and it worked. I just want to know about the "if-else" code which doesn't work. Thanks

2
  • 4
    checkForVisible is a boolean, you're comparing it to "visible" again for some reason. Just use if(checkForVisible). Commented Apr 21, 2016 at 14:10
  • 1
    The answers below are correct, particularly using toggle, but you should try stepping through your code with a debugger and setting a break point on if(checkForVisible == "visible") { to see what value the var checkForVisible holds. Learning how to do this will allow you to debug these problems yourself in future. Commented Apr 21, 2016 at 14:21

3 Answers 3

7

You do this:

var checkForVisible = img.style.visibility == "visible";

The == "visible" makes it the result of the equals expression so it's going to be true or false.

Your if/else is checkForVisible == "visible" which won't work because is will only be true or false. You only need to compare once.

if(img.style.visibility == "visible"){
        img.style.visibility = "hidden";
    }
    else{
        img.style.visibility = "visible";
    }
Sign up to request clarification or add additional context in comments.

Comments

2

Use toggle instead of if else.

function toggleImg() {
  var img = document.getElementById('pic');
  img.classList.toggle('hidden');

}
.visible {
  display: block;
}
.hidden {
  display: none;
}
<img src="img/somepic.jpg" id="pic">
<br/>

<a href="javascript:toggleImg()">Toggle Image</a>

Comments

1

There are mistakes. For example in the checkForVisible var. I'n not sure what you're trying to do but there are too many equals. You can try this out:

function toggleImg(){
    var img = document.getElementById('pic');

    img.style.visibility = "visible";

    if(img.style.visibility === "visible"){
        img.style.visibility = "hidden";
    }
    else{
        img.style.visibility = "visible";
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.