Question

In my HTML, I have a section in which I have JavaScript that adds an event listener which runs my game:

<div class="content">
<script>
        window.addEventListener('load', Game.start);
</script>
</div>

How do I make it so that the JavaScript is contained within the div above it? When it shows, the game is completely outside of it.

I'm using the crafty.js framework. Documentation here: http://craftyjs.com/api/

Was it helpful?

Solution 2

As mentioned in one of the comments, a div with the id "cr-stage" is important to crafty.js. However, you don't actually have to include it. If you leave it out, it will automatically be created.

<html>
  <head>
    <!-- this is the crafty.js library, which you could load from another server -->
    <script src="crafty.js"></script>

    <!-- this is the script where all your game's JS goes -->
    <script src="mygame.js"></script>

    <script>
      window.addEventListener('load', Game.start);
    </script>
  </head>
  <body>
  </body>
</html>

If you use the above, you will get a cr-stage id created for you.

Another thing that might be relevant to your question is if you want to center the cr-stage and remove a small gap that automatically appears above it. To do that, use this code:

<html>
  <head>
    <!-- this is the crafty.js library, which you could load from another server -->
    <script src="crafty.js"></script>

    <!-- this is the script where all your game's JS goes -->
    <script src="mygame.js"></script>

    <script>
      window.addEventListener('load', Game.start);
    </script>

    <style type="text/css">
      /* remove the small gap at the top */
      body { margin-top: 0 }

      /* horizontally center your stage on the page */
      #cr-stage { margin: 0 auto 0 }
    </style>
  </head>
  <body>
  </body>
</html>

OTHER TIPS

Not sure what Game.start does. However, the script doesn't need to be in the container element. You can simply have something like that:

<html>
  <head>
    <script>
      // here some library that defines `Game.start`
      window.addEventListener('load', Game.start);
    </script>
  </head>
  <body>
    <div class="content" id="game-container"></div>
  </body>
</html>

Inside Game.start you have to use document.getElementById("game-container") in order to get a reference to the element you need, and then use that to add the nodes you want to.

You need to give that Div an ID then modify the javascript to load the object in your div's id.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top