0
<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>  
4
  • 2
    @Guy Maybe OP isn't using some bloated library? Commented Feb 25, 2013 at 21:40
  • Have you heard of jQuery.toggle()? api.jquery.com/toggle will solve the problem, I deeply suggest using it for simple problems such as these as all the code implementation is done for you. Commented Feb 25, 2013 at 21:44
  • 2
    This definitely is a beginner's question, but it's not deserving the downvotes IMHO... Commented Feb 25, 2013 at 21:46
  • @alexander.biskop Agreed. It's got enough info to know the context, it's got code of what he has so far, and a simple question about how to take things to the next step. It's a well asked question! Commented Feb 25, 2013 at 21:52

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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

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

Comments

0

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

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.