செவ்வாய், 20 ஜூன், 2017

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>  
share

2  
@Guy Maybe OP isn't using some bloated library? – PeeHaa Feb 25 '13 at 21:40
    
@PeeHaa, perhaps. – gmaliar Feb 25 '13 at 21:43
    
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. – gmaliar Feb 25 '13 at 21:44
2  
This definitely is a beginner's question, but it's not deserving the downvotes IMHO... – alexander.biskop Feb 25 '13 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! – Alex Wayne Feb 25 '13 at 21:52
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.
share

The wonders of jQuery - http://jsfiddle.net/PbG3t/
$(function() {
    $('#button').click(function() {
        $('#someimage').toggle();
    });
 });
share

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>

கருத்துகள் இல்லை:

கருத்துரையிடுக