DeadPixle DeadPixle - 24 days ago 13
HTML Question

how do you display a image from a if statement

<img id="myImg">
<script>
var deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52];

function myFunction() {
deck.sort(function(a, b) {
return 0.5 - Math.random()
});
deck.shift();
document.getElementById("demo").innerHTML = deck;
document.getElementById("player1").innerHTML = deck[0];

if (deck[0] == '1') {
document.getElementById("myImg").style.display = 'inline';
} else if (deck[0] == '2') {
alert("I am an alert box!");


This is the code I got. I need it to make a image display in a specific location.

Answer

A few errors:

  • Missing }
  • You are comparing array indexed elements to string,example if == '2' instead of numbers

    See snippet

    note: I added an image and set its display property to none.

    If the snippet is run several times and you are lucky enough to obtain an array with first and second elements as 1 and 2 respectively, You'll notice the if statements are executed

    img {
      display: none;
    }
    <img id="myImg" src="https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcTkb6sdx_0T-5Pb34CB1_x1ILIQIErjC5C1kA8cIrxDclawMiMK">
    <div id="demo"></div>
    <div id="player1"></div>
    <script>
      var deck = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52];
    
      function myFunction() {
        deck.sort(function(a, b) {
          return 0.5 - Math.random()
        });
        deck.shift();
        document.getElementById("demo").innerHTML = deck;
        document.getElementById("player1").innerHTML = deck[0];
        if (deck[0] == 1) {
          document.getElementById("myImg").style.display = 'inline';
        } else if (deck[0] == 2) {
          alert("I am an alert box!");
        }
      }
      myFunction()
    </script>

  • Comments