Tina Tina - 6 months ago 35
Javascript Question

inner HTML using functions or similar

I am creating a memory game and setting up the game area in the body as a div which then I am supposed to add the table to from the script. I have done so using a function setGame(), which calls the game card images from a saved folder. This is what I have so far, but it does not work. The inner.html does not call the full function but rather draws one image and writes the remainder of the function script as text. Please help!

<html>
<head>
</head>
<body>
<div id="gameArea"></div>
<script>
var divRef = document.getElementById('gameArea');
function setGame()
{document.writeln('<table>')
for(var i=0; i<4; i++) {
document.writeln('<tr>');
for(var j=0; j<12; j++) {
document.writeln('<td><img id="'+parseInt(j+i*13)+'" src="back.gif" onclick="selectCard()" width="100" height="120" /></td>');}
document.writeln('</tr>');}
document.writeln('</table>')}
{divRef.innerHTML =setGame}
</script>
</body>
</html>

Answer

document.writeln is the wrong function to use. It always writes the given HTML directly into the document right after the <script> element where that code is written. But you want to save that HTML in a string and return it from your function setGame.

The other mistake you are making is in the line divRef.innerHTML = setGame. setGame is just the name of the function, so you are trying to set the div contents to a function. That is why the source code is shown on the page. Instead you should call the function with parentheses like setGame(), so the return value of the function is calculated.

Fixing these problems plus some other small problems, such as unnecessary use of parseInt and formatting problems, gives you this:

var divRef = document.getElementById('gameArea');

function setGame() {
  var html = '';
  
  html += '<table>';
  for (var i = 0; i < 4; i++) {
    html += '<tr>';
    for (var j = 0; j < 12; j++) {
      html += '<td><img id="' + (j + i * 13) + '" src="back.gif" onclick="selectCard()" width="100" height="120" /></td>';
    }
    html += '</tr>';
  }
  html += '</table>';
  
  return html;
}

divRef.innerHTML = setGame();
<div id="gameArea"></div>

Putting them together in the HTML:

<html>

<head>
</head>

<body>
  <div id="gameArea"></div>

  <script>
    var divRef = document.getElementById('gameArea');

    function setGame() {
      var html = '';

      html += '<table>';
      for (var i = 0; i < 4; i++) {
        html += '<tr>';
        for (var j = 0; j < 12; j++) {
          html += '<td><img id="' + (j + i * 13) + '" src="back.gif" onclick="selectCard()" width="100" height="120" /></td>';
        }
        html += '</tr>';
      }
      html += '</table>';

      return html;
    }

    divRef.innerHTML = setGame();
  </script>
</body>

</html>