Velvet Star Monitor

Standout celebrity highlights with iconic style.

updates

Show/hide image with JavaScript

Writer Emily Wong

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.

6 Answers

If you already have a JavaScript function called showImage defined to show the image, you can link as such:

<a href="javascript:showImage()">show image</a>

If you need help defining the function, I would try:

function showImage() { var img = document.getElementById('myImageId'); img.style.visibility = 'visible';
}

Or, better yet,

function setImageVisible(id, visible) { var img = document.getElementById(id); img.style.visibility = (visible ? 'visible' : 'hidden');
}

Then, your links would be:

<a href="javascript:setImageVisible('myImageId', true)">show image</a>
<a href="javascript:setImageVisible('myImageId', false)">hide image</a>
1

It's pretty simple.

HTML:

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

JavaScript:

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

CSS:

#theImage { visibility: hidden; }
2

You can do this with jquery just visit to get the link then do something like this

<a>Show Image</a>
<img src="">
<script src="//"></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>Show Image</a>
<img src="">
<script src="//"></script>
<script> $(document).ready(function(){ $('#show_image').on("click", function(){ $('#my_images').toggle(); }); });
</script>

This is working code:

<html> <body bgcolor=cyan> <img src ="backgr1.JPG" width="310" height="392"/> <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>

Here is a working example: (using jQuery)

<img src="">
<a>click to toggle</a>
img {display: none;}
a {cursor: pointer; color: blue;}
$('#toggle').click(function() { $('#tiger').toggle();
});

HTML

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

JavaScript:

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

CSS:

#theImage { display:none; }

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy