Skip to content
← Back to Community
How do I display images on the click of a button?
Profile icon
KatieKiely

I've made this website and on the 'More Information' Page I want to display an image when the button is pressed but my javascript doesn't seem to be working. Any help would be appreciated!

Answered by Grify [earned 5 cycles]
View Answer
Voters
Profile icon
KemberlyLoja
Profile icon
KatieKiely
Comments
hotnewtop
Profile icon
Grify

I don't exactly understand what you are trying to do. Could you be more specific?

Profile icon
KatieKiely

@Grify I want it so when the button labelled 'field' is clicked on the 'More Information' page, a picture shows up below the button in the 'div' tag

Profile icon
Grify

@KatieKiely show_image is not a javascript function, you'll have to do this differently.

A few things come to mind, namely using css hidden and visible from classes on the image and manually adding and removing the image html from the div with js

Profile icon
Grify

@Grify To do this with css,

css:
img.active {display: block;}
img {display: none;}
js:
function showFieldImage(){
document.getElementById('imagefield').classList.add('active')
}

html:
Field

this works because it gives the image a class which makes it visible in css, showing the romance of these three beautiful languages!

Profile icon
KatieKiely

@Grify This is working, thanks so much!

Profile icon
Grify

@KatieKiely Anytime :D

Profile icon
AdCharity

What file and what line?

Method 1

add an image to index.html, call it any id/class. Change its css to display: none so that it is hidden.
in script.js make a click event (either onclick/addEventListener) and do document.getElementById('the id of the image').style.display = 'block', which will show the image.

Method 2

You can use js to create an image using document.createElement() https://www.geeksforgeeks.org/how-to-create-an-image-element-dynamically-using-javascript/