0

I am very new to javascript and to test my abilities on what I have recently learnt, I have decided to create a hangman game.

One thing which I have not been taught is to show images in html from javascript.

A key part of my hangman game is that when the users lives decrease from 8 down to 0 which is game over, I want different hangman images to be shown to correspond with the lives that have reduced.

The code which I have does not show the images on the website like I expected. Why is this ?

            if (lives ==7){
            <img src="Hangman-0.png">
             }

Thank you

Lauren
  • 11
  • 4
  • This looks like JSX, however i dont think thats what you meant :) – Jonas Wilms Apr 12 '18 at 16:45
  • 1
    You're confusing javascript and HTML syntax. To create an HTML tag using javascript, you should consider using [`document.createElement`](https://developer.mozilla.org/fr/docs/Web/API/Document/createElement). Or for the more specific `img` tag, you can use the [`Image`](https://developer.mozilla.org/fr/docs/Web/API/HTMLImageElement/Image) API. – Ulysse BN Apr 12 '18 at 16:46

2 Answers2

0

You want to have the image element use an id

<img id="hmImg" src=""/>

Then in javascript:

if (lives == 7) {
document.getElementById("hmImg").src = 'url/of/image';
}
Allan
  • 2,889
  • 2
  • 27
  • 38
0

You write javascript to manipulate the DOM, which is what the users eventually sees. Besides <img src="Hangman-0.png"> is not valid javascript, so that would raise an error in console.

To dynamically inject images using javascript, you need to find a node in DOM where to insert your image. Let's say you want your image inside a div with id image

if (lives ==7){
   var newElement = document.createElement("img");
   newElement.setAttribute("src", "Hangman-0.png");
   document.getElementById("image").appendChild(newElement)     
}
Abhishek Gupta
  • 1,297
  • 13
  • 28