Ask coding questions

← Back to all posts
I'm not sure how to assign a script to a button
MatthewX (139)

i tried assigning the script to onclick for the html button. i also tried writing the function in between <script></script>, but it didnt work. Is there any other way to assign a script to a button???

Answered by Coder100 (6994) [earned 5 cycles]
View Answer
Coder100 (6994)

Hi! You are confusing javascript with java...

function infernoa(){  
  let charhp = 100;
  let chars = 100;
  let inferno = Math.floor(Math.random() * 20);
  let pikahp = 100;
  let pikahp = pikahp - inferno;
  let chars = chars - 20;

Here's the fixed code.

MatthewX (139)

@Coder100 Oh, i didnt know that my bad.

MatthewX (139)

@Coder100 wait, but how do i assign the code to the onclick event for the button?

Coder100 (6994)

so your code becomes:

<button onclick="infernoa()"></button>

<!-- ... some code ... -->

<script src="script.js"></script>


MatthewX (139)

@Coder100 wdym by some code. Do I write the code where the arrows are?

MatthewX (139)

@Coder100 But how come the random attack does like 90 dmg i want it to do around 0-20 dmg

MatthewX (139)

@Coder100 And also do you have an idea of how to add a health thing like Health: {} where you can change it whenever the health is loss?

MatthewX (139)

@Coder100 nvm about the random thing.

ironblockhd (345)

You use java functions but you have to use javascript (they're not the same)