user3658616 user3658616 - 2 months ago 15
HTML Question

activate javascript block of code

I have a Javascript block of code but I don't know how to activate it.
I would like it to be activated with a HTML button but I don't know if it's possible. I'm just beginning in coding =P

Here's the code:

var randomFlavour = Math.random() * 10;

if (randomFlavour < 1) {
var randomFlavour = "chocolate";
} else if (randomFlavour < 2) {
var randomFlavour = "vanilla";
} else if (randomFlavour < 3) {
var randomFlavour = "pistachio";
} else if (randomFlavour < 4) {
var randomFlavour = "strawberry";
} else if (randomFlavour < 5) {
var randomFlavour = "cotton candy";
} else if (randomFlavour < 6) {
var randomFlavour = "cookie dough";
} else if (randomFlavour < 7) {
var randomFlavour = "bubblegum";
} else if (randomFlavour < 8) {
var randomFlavour = "peanut butter";
} else if (randomFlavour < 9) {
var randomFlavour = "mint";
} else {
var randomFlavour = "gingerbread man";
}

console.log("Hello. I would like to have" + " " + randomFlavour + " " + "ice cream please.");

Answer

Wrap your js code in a function. Set the onclick listener of the button to call your function.

<html>
    <head>
        <script>
            function myFunction() {
                ... all of your javascript code ...
            }
        </script>
    </head>
    <body>
        <button onclick="myFunction()">My Button</button>
    </body>
</html>
Comments