简体   繁体   中英

Hide and then show an image using Javascript

<script>  
function showhide() {  
document.getElementById('someimage').style.visibility="hidden";   
        }  
</script>  

At the moment I am able to hide the image, however then I have no way to show it again. How can I hide and then be able to show an image when clicking a button using javascript?

Here's the button:

<body>  
<input type="button" onclick="showhide()" />   
</body>  

Simply check what the current state is, and then act accordingly.

function showhide() {
    var img = document.getElementById('someimage');
    if (img.style.visibility === 'hidden') {
        // Currently hidden, make it visible
        img.style.visibility = "visible";
    } else {
        // Currently visible, make it hidden
        img.style.visibility = "hidden";
    }
}

And a quick note about jQuery to all those suggesting it.

For simple things like this, there is no need to include a big DOM manipulation library. If you are doing a lot of DOM manipulations like this in a more complex application, then jQuery starts to make more sense to include.

But it's also important to understand what jQuery is doing for you under the hood when you use it.

The wonders of jQuery - http://jsfiddle.net/PbG3t/

$(function() {
    $('#button').click(function() {
        $('#someimage').toggle();
    });
 });

If you are using jQuery, you can use the ( .toggle ) method which simplifies things a lot:

$('#someimage').toggle();

If you want to stick with a hand-crafted solution, I guess your code is actually missing the deciding bit that sets the element's visibility back to visible. Try:

<script>  
  function showhide() {
      var element = document.getElementById('someimage');
      element.style.visibility = element.style.visibility == 'visible' 
          ? 'hidden' 
          : 'visible';   
  }  
</script>

Cheers, Alex

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM