Mika H. Mika H. - 12 days ago 8
Javascript Question

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.

Answer

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>