Ways to restart the random number generator in JavaScript

Just embarked on my first JavaScript project and I'm aiming to create a personalized slot machine. However, I've hit a roadblock - I can't figure out how to restart my program or the function for generating new random values repeatedly. Here's what my code looks like so far:

var randomX1 = Math.ceil(Math.random() * 10 );
var randomX2 = Math.ceil(Math.random() * 10 );
var randomX3 = Math.ceil(Math.random() * 10 );

function randomClickX() {
    document.getElementById("randomX1").innerHTML = randomX1;
    document.getElementById("randomX2").innerHTML = randomX2;
    document.getElementById("randomX3").innerHTML = randomX3;

    var output = "Play again";
    if (randomX1 === randomX2) {
    if(randomX2 === randomX3) {
        var output = "Jackpot";
        }
    }


    var result = output;
    function clickResult() {
        document.getElementById("result").innerHTML = result;
    }
    document.getElementById('spanId').innerHTML = result;
};
.slot-container {
    border: 5px solid red;
    vertical-align: middle;
    font-size: 50px;
    font-family: Leelawadee UI Semilight, Calibri, Arial;
    width: 90%;
    margin: auto;
    height: 0;            
    padding-bottom: 30%;   
}

(remaining CSS and HTML code remains as is)

I currently have to refresh the HTML file in order to click the SPIN button again and generate new random numbers. I believe the key lies in creating a comprehensive function that is called at the end of the SPIN function. I just need some guidance on how to implement this successfully. Any help would be greatly appreciated!

Regards, Jonas

Answer №1

One way to improve the code is to move the random number generation logic inside the click method.

function randomClickX() {
    var randomNumber1 = Math.ceil(Math.random() * 10 );
    var randomNumber2 = Math.ceil(Math.random() * 10 );
    var randomNumber3 = Math.ceil(Math.random() * 10 );

    document.getElementById("randomX1").innerHTML = randomNumber1;
    document.getElementById("randomX2").innerHTML = randomNumber2;
    document.getElementById("randomX3").innerHTML = randomNumber3;

    var output = "Play again";
    if (randomNumber1 === randomNumber2) {
        if(randomNumber2 === randomNumber3) {
            output = "Jackpot";
        }
    }

    var result = output;
    function clickResult() {
        document.getElementById("result").innerHTML = result;
    }
    document.getElementById('spanId').innerHTML = result;
};
.slot-container {
    border: 5px solid red;
    vertical-align: middle;
    font-size: 50px;
    font-family: Leelawadee UI Semilight, Calibri, Arial;
    width: 90%;
    margin: auto;
    height: 0;            
    padding-bottom: 30%;   
}

.slot {
    border: 3px solid green;
    height: 0;
    padding-bottom: 30%;
    width: 32%;
    margin-right: 1%;
    margin-top: 1%;
    margin-bottom: 1%;
    float: left; 
    box-sizing: border-box;
}

#slot1 {
    margin-left: 1%;
}

h1 {
    color: #FC3FD3;
    text-align: center;
    font-family: Century Gothic;
    font-size: 5em;
    height: 50px;
}

p {
    text-align: center;
    vertical-align: middle;
    justify-content: center;
}

button {
    position: relative;
    font-size:20px;
    display: block;
    background-color: white;
    color: black;
    border: 2px solid green;
    width: 90%;
    position: middle;
    margin-left: auto;
    margin-right: auto;
    margin-top: 10px;
    margin-bottom: 10px;
}

button:hover {
    background-color: green;
}

button.spin-button {
    color: blue;
    position: absolute;
    height: 20%;
}

.answer {
    font-family: Century Gothic;
    font-size: 20px;
    color: red;
    text-align: center;
    margin-top: 10px;
}

ul.menubar {
    list-style-type: none; 
    margin: 0;
    padding: 0;
    overflow: hidden;
    background-color: #008000;
}

ul.menubar li {
    float: left; 
}

ul.menubar li a {
    color: black;
    display: inline-block;
    text-align: center;
    padding:15px 20px;
    text-decoration: none; 
    transition: 0.3s; 
    font-family: Century Gothic;
}

ul.menubar li a:hover {
    background-color: #00A300;
}
<!DOCTYPE HTML>

<html>

<head>
  <title>Slot Machine</title>
  <script type="text/javascript" src="#.js"></script>
  <link type="text/css" rel="stylesheet" href="#.css" />
</head>

<body>
    <ul class="menubar" id=topmenubar>
        <li><a href="#linkHome">Home</a></li> <!-- bedeutet '#' gleicher Link + Ergänzung?-->
        <li><a href="#linkContact">Contact</a></a></li>
        <li><a href="#linkAbout">About</a></li>
    </ul>

    <h1>1-10</h1>

    <button type="button" id="spin-button" class="button" onClick="randomClickX()">SPIN</button>
    <div class="slot-container">
        <div id="slot1" class="slot">
            <p> <!-- Your random number: --> <a id="randomX1">0</a></p>
        </div>
        <div id="slot2" class="slot">
            <p> <!-- Your random number: --> <a id="randomX2">0</a></p>
        </div>
        <div id="slot3" class="slot">
            <p> <!-- Your random number: --> <a id="randomX3">0</a></p>
        </div>
        </div>
    </div>

    <div class="answer" id="spanId">Test #1<a id="spanId"> </div>

</body>

</html>

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

Using jQuery ajax in PHP, the ability to remove retrieved information from a different page is a

I'm currently working on a jQuery AJAX PHP application that allows for adding, deleting, and displaying records using switch case statements to streamline the code. Everything seems to be functioning correctly with inserting and displaying records, bu ...

Printing doesn't display CSS styling

I am currently working on creating a function to change the font color, however, I am facing issues with the CSS when it comes to printing. Here is the code I have: $('#draw').on('click', 'p', function () { if($(this).ha ...

Setting a variable in a v-tab using Vuetify now only takes 2 easy clicks!

I'm currently utilizing Vuetify and vuejs to develop a tab system with 3 tabs. The tabs are being switched dynamically by binding to the href of a v-tab. Each time I click on a tab, the value of the speed variable is modified. However, I'm encoun ...

What is the best way to retrieve the name of a dynamic form in a Controller

How can I retrieve the dynamic form name in my controller? See below for the code snippet: HTML <form name="{{myForm}}" novalidate> <input type="text" ng-model="username" name="username" required/> <span ng-show="(submit & ...

Leveraging $http or $timeout in conjunction with $stateProvider in AngularJS

I am seeking guidance on loading a template for a specific state in Angular using $http after coming across this question on Stack Overflow: Is it possible to load a template via AJAX request for UI-Router in Angular? The documentation for ui.router demon ...

Can you explain the concept of themes in Material UI?

I am trying to wrap my head around the concept of themes and what they are meant to represent. I have gone through the documentation, but I still find it confusing. For instance, here is a snippet of code that I am referring to. I just want to understand ...

Learn how to efficiently reload a card in React upon submitting new data

Is there a way to automatically refresh the card component after submitting data without having to manually refresh the page? I've tried using useEffect but it's not updating the data even though the value is changing. Any suggestions on how to r ...

Transmitting HTML content to the browser from the client using Node.js

Quoted from: Book - "Getting MEAN with Mongo, Express.." When it comes to responding to requests in your application by sending HTML to the browser, Express simplifies this process compared to native Node.js. With support for various templating e ...

Exploring the Dev Tools Console feature in Excel for Windows

I have developed an Excel add-in using AngularJS. I utilize <div ng-show="isLoggedIn">...</div> and <div ng-show="!isLoggedIn">...</div> to manage different content based on the value of $scope.isLoggedIn. While it functions well i ...

Is there a way to automatically add a div to the window as the user scrolls and then hide the div when they scroll back to the

Seeking assistance with creating a function that will add a 'sticky' class to the menu when the user scrolls down to the middle, and then append a div when the 'sticky' class is present. Currently facing issues where the div keeps appen ...

What is the best way to retrieve a JSON string in JavaScript after making a jQuery AJAX request?

Why am I only seeing {} in the console log when ajax calling my user.php file? $.ajax({ url: '.../models/user.php', type: 'POST', dataType: "json", data: {username: username, password:password, func:func}, succ ...

Tips for deleting a chunk in Next.js

Currently, I am involved in a Next.js and Reactjs project. In an effort to optimize performance and address Lighthouse recommendations regarding unused JS files, I am exploring the possibility of removing chunk js files from the _next/static/chunks direc ...

Tips for creating multiple functions within a single JavaScript function

Is there a way to combine these two similar functions into one in order to compress the JavaScript code? They both serve the same purpose but target different CSS classes. The goal is to highlight different images when hovering over specific list items - ...

In Java, the output of jsExecuteScript returns null, whereas in the browser console, it returns a String value

While running a script in the console of the browser on the aforementioned page, I encountered the following: document.querySelector('.subscribe_form input').value The placeholder value displayed was "Enter your email address." However, when at ...

Is there an issue with the jQuery ajax function when it comes to sending the RegistrationId to our server?

Beginning to work with the pushNotification service for my Android app, I successfully received a registration ID from the GCM server and attempted to send this ID to our server using a jQuery AJAX function. My intention was to send this ID after the user ...

Locate the database user based on any parameter provided in the request

I need to search for users in the database using any of three different fields. In Postman, I have set up the following paths: http://localhost:8082/api/users/617473029f80eda3643a7fdd http://localhost:8082/api/users/Michael http://localhost:8082/api/use ...

What is the best way to organize a json based on numerical values?

Can anyone guide me through sorting a JSON data into an array based on numeric value, and then explain how to efficiently access that information? {"362439239671087109":{"coins":19},"178538363954003968":{"coins":18},"234255082345070592":{"coins":137}} Th ...

What is a more streamlined method for connecting variables to buttons?

Is there a more efficient way to increment specific variables by 1 with 3 different buttons, other than writing 3 separate onclick functions? I'm aware of using data attributes to connect buttons with the correct elements, but I'm not sure how to ...

Using VueJS: accessing this.$store within component data property

I am interested in utilizing the data from my Vuex store in both my app and template. My Vuex store: var Vue = require('vue'); var Vuex = require('vuex'); Vue.use(Vuex) let store = new Vuex.Store({ state: { user: ...

Uncover the reason behind the application's crash with Titanium

If we encounter non-crashing errors, utilizing LogCatcher can help by pinpointing which Javascript code is causing the issue. However, in the event of a crash, there's no time for logging Javascript errors. In such cases, integrating tools like ARCA ...