0

I have the following code. I am trying to make a dice roller. However, the button doesn't seem to be functioning. Any ideas what I am missing? Is my EJS incorrect?

  <div class="dicecontainer">
    <div class="dice"><p id="rollresult">Result</p></div>

      <%  function roll() { %>
        <%  var result =  Math.floor(Math.random() * 6 + 1); %> 
        <% document.getElementById("rollresult").innerHTML=result; %>
      <%  }; %>

     <button onclick="roll()">Roll Dice</button> 
 </div>
Soonerdev
  • 48
  • 5
  • EJS is *server-side* JS, you're trying to write *client-side* code in there. (And I think your syntax is wrong for EJS anyway: I don't think you can dip in and out of EJS blocks in the middle of a statement) – Quentin Feb 03 '19 at 21:38
  • Your answer in combination with the answer below solved the problem. I had other EJS that was working fine in my code, but I didn't realize it was all server-side JS. The script tags below solved the problem. Thank you! – Soonerdev Feb 03 '19 at 21:49

1 Answers1

0

Why do you write javascript code inside ejs tags? It is by far more simple and easy to place your code inside script tag like this:

<div class="dicecontainer">
    <div class="dice"><p id="rollresult">Result</p></div>
     <button onclick="roll()">Roll Dice</button> 
 </div>
<script type="text/javascript">
  function roll() {
      var result =  Math.floor(Math.random() * 6 + 1);
      document.getElementById("rollresult").innerHTML=result;
  };
</script>
dimitris tseggenes
  • 3,031
  • 2
  • 16
  • 23