Steps for implementing a reset button in a JavaScript slot machine game

I need assistance with implementing a reset button for my slot machine game prototype written in JS. I attempted to create a playAgain function to restart the game by calling the main game function, but it's not working as expected. Do I need to pass a parameter to make it work? Any help would be appreciated!

const num1 = document.getElementById("num-1");
const num2 = document.getElementById("num-2");
const num3 = document.getElementById("num-3");
const message = document.getElementById("message")
const button = document.getElementById("button");

const random1 = Math.floor(Math.random() * 9) + 1;
const random2 = Math.floor(Math.random() * 9) + 1;
const random3 = Math.floor(Math.random() * 9) + 1;

button.addEventListener("click", checkEquality);

function checkEquality() {
    num1.innerHTML = random1;
    num2.innerHTML = random2;
    num3.innerHTML = random3;
    if (random1 === random2 && random1 === random3 && random2 === random3) {
        message.innerHTML = "Congratulations, you won!"
    } else {
        message.innerHTML = "Sorry, you lost!"
    }
    button.innerHTML = "GIVE IT ANOTHER GO!"
}
button.addEventListener("click", playAgain)
function playAgain() {
    if(num1 !== "?" && num2 !== "?" && num3 !== "?") {
        message.innerHTML = "";
        checkEquality()
    }
}
<h1>Slot Machine</h1>
<div>
    <p id="num-1">?</p>
    <p id="num-2">?</p>
    <p id="num-3">?</p>
</div>
<p id="message"></p>
<button id="button">GIVE IT A GO!</button>

Answer №1

For your function to work with different random numbers each time, make sure to include them inside the function itself. If you use const, remember that the value cannot be changed later on.

const num1 = document.getElementById("num-1");
    const num2 = document.getElementById("num-2");
    const num3 = document.getElementById("num-3");
    const message = document.getElementById("message")
    const button = document.getElementById("button");
    
    button.addEventListener("click", checkEquality);
    
    function checkEquality() {
        var random1 = Math.floor(Math.random() * 9) + 1;
        var random2 = Math.floor(Math.random() * 9) + 1;
        var random3 = Math.floor(Math.random() * 9) + 1;
        num1.innerHTML = random1;
        num2.innerHTML = random2;
        num3.innerHTML = random3;
        if (random1 === random2 && random1 === random3 && random2 === random3) {
            message.innerHTML = "Great job, you've won!"
        } else {
            message.innerHTML = "Oops, better luck next time!"
        }
        button.innerHTML = "TRY AGAIN!"
    }
    button.addEventListener("click", playAgain)
    function playAgain() {
        if(num1 !== "?" && num2 !== "?" && num3 !== "?") {
            message.innerHTML = "";
            checkEquality()
        }
    }
<html>
    <body>
        <h1>Slot Machine</h1>
        <div>
            <p id="num-1">?</p>
            <p id="num-2">?</p>
            <p id="num-3">?</p>
        </div>
        <p id="message"></p>
        <button id="button">GIVE IT A GO!</button>
        
    
        <script src="script.js"></script>
    </body>
    </html>

Answer №2

It appears that the issue lies in using a single button for multiple actions.

To remedy this:

button.removeEventListener("click",checkEquality);
button.addEventListener("click",playAgain);

In the checkEquality function, you can apply a similar approach to the playAgain function.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

``Why is it that the JavaScript code is unable to find the maximum or minimum sum? Let's

function calculateMinMaxSums(arr) { // Custom code implementation let max = Math.max(...arr); let min = Math.min(...arr); let minsum = 0; let maxsum = 0; for (let x in arr) { if (arr[x] != max) { minsum += arr[x]; }; if (arr[x ...

JS Executing functions in a pop-up window

Recently, I have been immersing myself in learning JS and experimenting with webpage interactions. It started with scraping data, but now I am also venturing into performing actions on specific webpages. For example, there is a webpage that features a butt ...

The toggle-input component I implemented in React is not providing the desired level of accessibility

Having an accessibility issue with a toggle input while using VoiceOver on a Mac. The problem is that when I turn the toggle off, VoiceOver says it's on, and vice versa. How can I fix this so that VoiceOver accurately states whether the toggle is on o ...

Incorporate action icons (such as edit and delete) into a table in React.js using material-ui

Within my existing table, I utilized a library known as react-bootstrap-table-next This library effectively displays data in a table format with values originating from a JSON response Now, my goal is to integrate an Action column that includes options f ...

How come the data from the Firebase real-time database is only displaying in the console and not on the page when using Vue.js?

I am encountering an issue while trying to display a value stored in my Firebase Realtime Database using the {{ exams.name }} syntax in Vue. Although I can see the value when I console.log it, it does not render on the page. However, when I attempted the s ...

Running a JavaScript function within a designated div element

I'm currently facing an issue with executing a javascript function - onload only in a specific div. I seem to be stuck on this problem, so if anyone could offer some assistance, I would greatly appreciate it. Thank you very much in advance! functio ...

Looking for a script to automate clicking on a specific web element using JavaScript

When working with Selenium, we utilize an action to interact with an element by clicking on it at specific coordinates (X, Y). action.MoveToElement(element, X, Y).Click().Build().Perform() I am looking to achieve the same functionality using Javascript. ...

Tips for correctly implementing Headers in AngularJS version 1.6

Currently, I am attempting to incorporate headers in a GET request using the $http method. This is the snippet of code that I have implemented: this.http.defaults.headers.common['Authorization'] = 'Bearer mytoken123123'; this.http.def ...

What could be the reason my div is not being hidden in jQuery?

Creating a quiz layout for school is my current project, and I'm just getting started. My goal is to have the questions disappear once the 'next question' button is clicked. The issue arises after the second question because instead of the ...

Guidance on toggling elements visibility using Session Service in AngularJS

After reading this response, I attempted to create two directives that would control the visibility of elements for the user. angular.module('app.directives').directive('deny', ['SessionTool', function (SessionTool) { ret ...

Implementing JSON methods in C# WebService to enable communication with external servers

Is it possible to integrate an asp.net web service written in C# into an HTML5/JavaScript website? The challenge is that the web service and client are located on different domains, requiring a cross-domain request. ...

What is the jquery alternative to the PHP 'if IP equals' condition?

I am curious to know if the following PHP 'if' conditions can be achieved in jquery or JavaScript, with a preference for jquery. if ($_SERVER['REMOTE_ADDR'] != '123.99.55.616') { // public doingness } if ($ ...

res.send No data being transmitted - in the realm of Express.js

I'm currently developing a calculator app using Express.js, but I seem to be encountering an issue with the res.send Method as I am not getting any response. My expectation is for my webpage to display the sum from the calculator.js file. Nodemon is a ...

What could be causing transition to not be recognized as an element in HTML?

<template> <header> <nav class="container"> <div class="branding"> <router-link class="header" :to="{name : 'Home'}">>FireBlogs</router-link> </div& ...

Why styled-components namespace problem in React Rollup build?

I designed a "UI Library" to be utilized in various projects using ReactJS + TypeScript + styled-components and Rollup. However, I am currently encountering issues with conflicting classNames. I am aware that styled-components offers a plugin for creating ...

Guide on decrypting a file encrypted with C# using Node JS

I currently have encrypted files in C# using DES and PKCS7 encryption. My objective is to decrypt these files in Node JS. The decryption code in C# that I am using appears like this: public string SSFile_Reader( string fileToDecrypt ) { DESCryptoService ...

Display a date that is asynchronously rendered for each item in the v-for loop

I am currently working on a project that involves an array of servers being displayed in a template using v-for. To receive dynamic data for each server, I have implemented the vue-nats library to subscribe them individually. methods: { subscribe(uuid) ...

NG6002 error: This error is showing up in the imports of AppModule, even though it has its own set of issues

Running Angular 12 locally is smooth with no errors in the project build. Local Configuration: Angular CLI: 12.0.5 Node: 12.16.3 Package Manager: npm 6.14.4 OS: win32 x64 Angular: 12.0.5 However, when attempting to build the project on a Linux se ...

Modifying a Json file in a Node application, while retaining the previously stored data

In my node script, I have a simple process where I update the db.json file via a form. The file is successfully updated, but when I try to render it in response for a GET or POST request, it only shows the previous results. var cors = require('cors&ap ...

`Count the number of rows needed to accommodate text line breaks within a div element`

Is there a method to determine the number of lines that text breaks into using the CSS property word-break: break-all? For example, if I have a div like this: <div>Sample text to check how many lines the text is broken into</div> And the corr ...