[javascript] Show/hide image with JavaScript

I have an HTML page with an image that I set to be invisible by CSS visibility: hidden. I want to make a link called "Show image", so that when I click on it, the image appears.

Now, I don't know how to make such a link, since normally a link with <a href=...> links to some other page. In my case, I want the link to invoke a JavaScript to display the image.

This question is related to javascript html

The answer is


It's pretty simple.

HTML:

<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>

JavaScript:

document.getElementById("showImage").onclick = function() {
    document.getElementById("theImage").style.visibility = "visible";
}

CSS:

#theImage { visibility: hidden; }

This is working code:

<html>
  <body bgcolor=cyan>
    <img src ="backgr1.JPG" id="my" width="310" height="392" style="position: absolute; top:92px; left:375px; visibility:hidden"/>
    <script type="text/javascript">
      function tend() {
        document.getElementById('my').style.visibility='visible';
      }
      function tn() {
        document.getElementById('my').style.visibility='hidden';
      }
    </script>
    <input type="button" onclick="tend()" value="back">
    <input type="button" onclick="tn()" value="close">
  </body>
</html>

You can do this with jquery just visit http://jquery.com/ to get the link then do something like this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').show('slow');
      });
   });
</script>

or if you would like the link to turn the image on and off do this

<a id="show_image">Show Image</a>
<img id="my_images" style="display:none;" src="http://myimages.com/img.png">

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
   $(document).ready(function(){
      $('#show_image').on("click", function(){
         $('#my_images').toggle();
      });
   });
</script>

Here is a working example: http://jsfiddle.net/rVBzt/ (using jQuery)

<img id="tiger" src="https://twimg0-a.akamaihd.net/profile_images/2642324404/46d743534606515238a9a12cfb4b264a.jpeg">

<a id="toggle">click to toggle</a>

img {display: none;}

a {cursor: pointer; color: blue;}

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

HTML

<img id="theImage" src="yourImage.png">
<a id="showImage">Show image</a>

JavaScript:

document.getElementById("showImage").onclick = function() {
    document.getElementById("theImage").style.display = "block";
}

CSS:

#theImage { display:none; }