Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Image visibility using javascript

Tags:

javascript

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

like image 337
surazzarus Avatar asked Feb 08 '23 05:02

surazzarus


1 Answers

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";
    }
like image 155
John Mc Avatar answered Feb 09 '23 22:02

John Mc