Learning the basics of JavaScript: Displaying the last number in an array and restarting a function

Hey there, I'm diving into the world of JavaScript and have set myself a challenge to create a simple bingo number machine. Check out my CodePen project here. I've successfully generated an array of 20 numbers, shuffled them, and added a marker to the board every time one is drawn. However, I have run into a couple of hurdles that are really bugging me.

Part One: I've implemented a reset button that clears the marked squares on the board. What I'm struggling with is figuring out how to reshuffle the array every time the reset button is pressed.

Part Two: In enhancing the functionality of the display, I've also included a section that shows the previously picked number. It's somewhat working, but I believe there's a more efficient way to do it. Additionally, I can't seem to hide the 'undefined' input that always appears at the beginning. I'm convinced there's a cleaner solution to handle this issue without needing to hide an undefined class.

Thank you in advance for your assistance, you guys are amazing!

P.S. I'm currently focusing on pure JavaScript for this project.

// Here's the function for shuffling the array

function shuffle(array) {
    var i = array.length,
        j = 0,
        temp;
        
    while (i--) {
        j = Math.floor(Math.random() * (i+1));

        // swap randomly chosen element with current element
        temp = array[i];
        array[i] = array[j];
        array[j] = temp;
    }

    return array;
}

// Input array
var ranNums = shuffle([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]);

// Functions to show next and last numbers
var f = 0;
var g = -1;

function nextNumber() {
  var randNum = ranNums[f++];
    document.getElementById('current').innerHTML = randNum; 
    
    if (f == ranNums.length) f = 0;   // reset to first element if you've reached the end
    
    document.getElementById("item" + randNum).className = "red";
}

function lastNumber() {
  var past = ranNums[g++];
    document.getElementById('previous').innerHTML = past;
  
  if(past === "undefined") {
    document.getElementById('previous').style.display='none';
  }
}
// Function to remove the class and reset the game
function resetNumbers() {
    for (var i = 0; i < ranNums.length; i++) {
       document.getElementById("item" + ranNums[i]).className = "";
      
    }
}
body {
  background-color: white;
  color: black;
  font-size: 20px;
  font-family: "Lucida Grande", Verdana,Arial, Helvetica, sans-serif;
}


h1, th {
  font-family: Georgia, "Times New Roman",Times, serif;
}


h1 {
  font-size: 28px;
}


table {
  border-collapse: separate;
  border-spacing: 30px;
  float: left;
}


th, td {
  padding: 30px;
  border: 2px black solid;
  text-align: center;
  width: 20%;
}

h2 {
  
}

button {
  
}

.red {
  background-color: red;
}
<h1>Bingo!</h1>
<h4>Current Number</h4>
<h2 id="current"></h2>
<h4>Previous Number</h4>
<h2 id="previous"></h2>
<table>
  <tr>
    <td id="item1"<h1>1</h1></td>
    <td id="item2"<h1>2</h1></td>
    <td id="item3"<h1>3</h1></td>
    <td id="item4"<h1>4</h1></td>
    <td id="item5"<h1>5</h1></td>
  </tr>
  <tr>
    <td id="item6"<h1>6</h1></td>
    <td id="item7"<h1>7</h1></td>
    <td id="item8"<h1>8</h1></td>
    <td id="item9"<h1>9</h1></td>
    <td id="item10"<h1>10</h1></td>
  </tr>
  <tr>
    <td id="item11"<h1>11</h1></td>
    <td id="item12"<h1>12</h1></td>
    <td id="item13"<h1>13</h1></td>
    <td id="item14"<h1>14</h1></td>
    <td id="item15"<h1>15</h1></td>
  </tr>
  <tr>
    <td id="item16"<h1>16</h1></td>
    <td id="item17"<h1>17</h1></td>
    <td id="item18"<h1>18</h1></td>
    <td id="item19"<h1>19</h1></td>
    <td id="item20"<h1>20</h1></td>
  </tr>
</table>


<button onclick="nextNumber(); lastNumber();">Next Number</button>

<button onclick="resetNumbers()">Reset</button>

Answer №1

To ensure that the previous number field is defined before displaying a value, you can use the following code:

document.getElementById('previous').innerHTML = past ? past : '';

This code utilizes the ternary operator to achieve the same result as the following if statement:

if (past) {//check if past is not null or undefined
  document.getElementById('previous').innerHTML = past;
else {
  document.getElementById('previous').innerHTML = '';
}

You can view the modified code pen here: codepen

Answer №2

When dealing with the undefined issue, make sure to check for undefined without converting it into a string. Undefined is simply undefined, so

if(past === "undefined") {
    document.getElementById('previous').style.display='none';
}

Should be

if(past === undefined) {
    document.getElementById('previous').style.display='none';
}

Regarding the reshuffle problem, you already have the shuffle function and the shuffled numbers stored in the ranNums variable. You can simply run an array of numbers through the shuffle function again and assign them to the ranNums variable when you call reset, like this:

// Removes the class and resets the game
function resetNumbers() {
    for (var i = 0; i < ranNums.length; i++) {
       document.getElementById("item" + ranNums[i]).className = "";

    }

  ranNums = shuffle([1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20]);
}

These are some basic solutions to your questions, but here are a few more suggestions for improvement:

  1. Keep your array of numbers to shuffle in a variable to avoid repetition in the reset function.
  2. Remove the number from Current Number when the reset button is pressed.
  3. Educate yourself on the differences between == and ===, as you are using both in different if statements.
  4. Learn about JavaScript objects and consider containing all your code within an object to prevent polluting the global namespace.

Overall, you're doing well! Keep up the good work!

Answer №3

Here are two suggestions for you:

  • First, consider using a new array to store 2 numbers (current and previous) and update it as needed instead of using loops for a simple check.

  • Secondly, utilize the ranNums array to create an HTML table, allowing you to easily regenerate the table when shuffling your number array.

I hope this idea helps you achieve your goal more efficiently. Feel free to ask if you need further clarification on anything. Thanks!

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

Displaying text on top of an image with the help of jquery and

I found a tutorial on this website that I'm trying to follow. It involves creating a fading/darkening effect on image rollover with text appearing, but I can't seem to get it to work even when starting from scratch. Despite having experience wit ...

`Next.js project experiencing issues with scroll trigger functionality`

I've been working on a gsap animation with a scroll trigger, and while the animation itself functions fine, it's not triggering as expected. The AnimationEffect code involves using gsap and scrolltrigger to create the animation. The Hero section ...

Exploring click event beyond React Component: Jest + Enzyme Testing

I am looking to create a Jest and Enzyme test for a component that includes an event listener. The purpose of the test is to ensure that when a mousedown event occurs outside of a specific HTML element, a change is triggered (for example, toggling a state ...

I am struggling to style a form effectively with CSS grid

I am working on setting up a 2-column HTML form using CSS grid. In the first column, I have labels placed on individual rows. In the second column, I have form elements also placed on individual rows. This is my initial attempt at this task and I am sti ...

Using jQuery to Generate an Automatically Updating Timer for Slideshow - Pausing on Mouse Click

My first slideshow with jQuery is up and running, but it's very basic and hard coded. I want to add an automatic scrolling effect every 8 seconds to the next item before looping back to the beginning. I have an idea on how to achieve this, but I want ...

Is it possible for me to invoke a div within a different component?

I am facing a challenge with a large div component. <div id='download> ..... </div> My goal is to incorporate this same component into a Paper within a Modal. <Modal> <Box sx={style} > <Paper elevation ...

Creating XPaths for HTML using Selenium: A step-by-step guide

What is the proper way to create an xpath expression for the following block of html? <li> <a href="/parade/storeus/browse/Home-Accents-Radios/_/N-1c7kmv"> Radios </a> </li> ...

Retrieve data from a local JSON file and showcase it in a list within a Next.js project. The error "Property 'data' does not exist on type String

Having trouble displaying the names of crates (which are filled with records/albums) from a local JSON file. The names aren't showing up and I'm wondering if I should be using params or if perhaps not stringifying the JSON would help. Visual Stud ...

The 'Component' you are trying to use cannot be rendered as a JSX component in Next.js

Take a look at the code in _app.tsx: function MyApp({ Component, pageProps }: AppProps) { return <Component {...pageProps} /> } An error is popping up during the project build process: Type error: 'Component' cannot be used as a JSX comp ...

Do factory and service represent examples of Declarative Programming within AngularJS?

Angular JS involves the declaration of services and factories. Services are created by declaring functions that we do not manually call ourselves. Could this be considered declarative programming, with the framework handling the imperative tasks? What ex ...

Ways to conceal a primary page section upon clicking a different tab

I am currently implementing the w3schools HOW TO - tabs feature on my website to create tabbed navigation. However, I'm running into an issue where clicking on tabs other than 'Home' still displays the 'Home' content along with the ...

Creating immersive 3D graphics using Three.js

Exploring three.js for the first time and experimenting with displaying a basic 3D model using three js, Vue, and Laravel. The 3D file can be found at /public/files/Tree1.3ds. Need help rendering the file in the Vue component with three js. Initially tried ...

What is the best way to access nested callback results from another file in a Node.js environment?

My API code can be found in the file api.js This is the content of api.js: var express = require('express'); var Vimeo = require('vimeo').Vimeo; var lib = new Vimeo('dfdfdfdfdfdfd', 'WDIt+kEVudfghjklkjhgfdfghjkjhgfMaG9X ...

Guide to implementing the HttpOnly flag in a Node.js and Express.js application

Hey there! I'm currently working on a project using node.js and I need to ensure that the HttpOnly flag is set to true for the header response. I've written this code snippet in my app.js file but it doesn't seem to be affecting the respons ...

Applying a class to an element in VueJS is not functioning as expected

My goal is to assign the class .testcolor to the div element when testvalue is true, and apply no class when it's false. I encountered an issue where the getClass method does not get called when added to :class attribute, but works fine when called f ...

Attempting to employ jQuery to generate a text input that allows for inputting multiple incorrect answers

I am putting together a webpage for a friend who has allergies. The idea is that users can input a food item, and the page will indicate whether or not my friend is allergic to it. I have compiled an array of his food allergies, and the goal is for the pag ...

How to center elements using Bootstrap 4 and flexbox styling

Just starting out in web development. I currently have the following HTML: <section class="boxes"> <div class="container-fluid"> <div class="row"> <div class="col-12 col-lg-4 box1&q ...

Preventing Cross-Site Scripting (XSS) when injecting data into a div

I am using Ajax to fetch data in JSON format and then parsing it into a template. Here is an example of the function: function noteTemplate(obj) { var date = obj.created_at.split(/[- :]/), dateTime = date[2] + '.' + date[1] + '. ...

fancybox thumbs will never function properly

I recently made the switch from using PrettyPhoto to FancyBox for my gallery, which utilizes Isotope for filtering and animations. However, I am encountering an issue where the images appear but the thumbnails are missing. In the developer tools, there is ...

Search timeout restriction

I have a function that makes a request to the server to retrieve data. Here is the code for it: export default class StatusChecker { constructor() { if (gon.search && gon.search.searched) { this.final_load(); } else { this.make_req ...