The start screen fails to display when clicking the restart button

I am struggling to get the restart button to display the start screen again. Even though I have called the restart function within the clearColors function, which should show the start screen, it hasn't been effective so far. Initially, in the fadeOutEffect function, I set the style of the main div (by classname .blankscreen) to none when the screen loads. This might be causing the issue. However, I can confirm that the restart function is functioning correctly since I changed the background color to red.

JS


function game() {

document.querySelector("#btn").addEventListener('click', fadeOutEffect);
document.querySelector("#rst").addEventListener('click', clearColors);

    let colors = ["red", "blue", "yellow", "purple", "green", "orange"];
    let tabledata = document.querySelectorAll('td');

    let i =0;
    tabledata.forEach(td => {
    console.log(td);
    td.addEventListener('click', () => {
        i++;
        if (i > 0) {  
           tabledata.forEach(td => {   
           let newcolor = colors[Math.floor(Math.random() * tabledata.length)];
           td.style.backgroundColor =`${newcolor}`;
           td.innerHTML=`${newcolor}`;
           
           })
        }   
    });
  });


  function fadeOutEffect() { //fade out on click
    var fadeTarget = document.querySelector(".blankscreen");
    var fadeEffect = setInterval(function () {
        if (!fadeTarget.style.opacity) {
            fadeTarget.style.opacity = 1;
        }
        if (fadeTarget.style.opacity > 0) {
            fadeTarget.style.opacity -= 0.1;
        } else {
            clearInterval(fadeEffect);
            setTimeout(() => {
            document.querySelector('.blankscreen').style.display="none";
            }, 500)
            document.querySelector('.reset').style.display="flex";
        }
    }, 100);
    
} 


function clearColors() {
    tabledata.forEach(td => {
        td.innerHTML="";
        td.style.backgroundColor="transparent";      
    })
    restart();
};

function restart() {
    setTimeout(() => {
        document.body.style.backgroundColor="red";
        document.querySelector('.blankscreen').style.display="flex";
    }, 500);
}

}

game(); // call game function

HTML

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>HTML 5 Boilerplate</title>
    <script src="https://code.jquery.com/jquery-3.6.0.js" integrity="sha256-H+K7U5CnXl1h5ywQfKtSj8PCmoN9aaq30gDh27Xc0jk=" crossorigin="anonymous"></script>
    <link rel="stylesheet" href="style.css">
  </head>
  <body>
      <div class="blankscreen startgame" id="start">
          <p>Start</p>
          <button type="button" id="btn">Start</button>
      </div>
      <div class="reset">
          <!-- <p>Reset</p> -->
          <button type="button" id="rst">Reset</button>
      </div>
      <table>
          <tr>
            <th id="">squares</th>
          </tr>
          <tr>
              <td>Red</td>
              <td>Blue</td>
              <td>Yellow</td>
          </tr>
          <tr>
            <td>Purple</td>
            <td>Green</td>
            <td>Orange</td>
        </tr>  
      </table>
    <script src="script.js"></script>
  </body>
</html>

CSS

body {
    height: 100vh;
}

.blankscreen {
    position: absolute;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    height: 232.5px;
    width: 314px;
    top: 232.5px;
    background-color: rgb(237, 103, 103);
    z-index: 99;
}


table {
    position: absolute;
    top: 232.5px;
    cursor: pointer;
    /* z-index: 99; */
}
td {
    height: 100px;
    width: 100px;
    text-align: center;
}
.reset {
    display: none; /* set to flex */
    flex-direction: row;
    justify-content: center;
    position: absolute;
    width: 314px;
    margin-top: 475px;

}
.reset #rst {
    position: absolute;
    top: 0;
    
}



Answer №1

I am currently undoing the actions of the Start button, and resetting the td elements back to their original positions according to the designated colors array.

function game() {
  document.querySelector("#btn").addEventListener("click", fadeOutEffect);
  document.querySelector("#rst").addEventListener("click", clearColors);

  let colors = ["red", "blue", "yellow", "purple", "green", "orange"];
  let tabledata = document.querySelectorAll("td");

  let i = 0;
  tabledata.forEach((td) => {
    console.log(td);
    td.addEventListener("click", () => {
      i++;
      if (i > 0) {
        tabledata.forEach((td) => {
          let newcolor = colors[Math.floor(Math.random() * tabledata.length)];
          td.style.backgroundColor = `${newcolor}`;
          td.innerHTML = `${newcolor}`;
        });
      }
    });
  });
  var fadeTarget = document.querySelector(".blankscreen");
  function fadeOutEffect() {
    //fading effect on click

    var fadeEffect = setInterval(function () {
      if (!fadeTarget.style.opacity) {
        fadeTarget.style.opacity = 1;
      }
      if (fadeTarget.style.opacity > 0) {
        fadeTarget.style.opacity -= 0.1;
      } else {
        clearInterval(fadeEffect);
        setTimeout(() => {
          fadeTarget.style.display = "none";
        }, 500);
        document.querySelector(".reset").style.display = "flex";
      }
    }, 100);
  }

  function clearColors() {
    fadeTarget.style.opacity = 1;
    fadeTarget.style.display = "";
    document.querySelector(".reset").style.display = "";
    tabledata.forEach((td, index) => {
      td.innerHTML = colors[index];
      td.style.backgroundColor = "";
    });
    //invoke restart();
  }

  function restart() {
    setTimeout(() => {
      document.body.style.backgroundColor = "red";
      document.querySelector(".blankscreen").style.display = "flex";
    }, 500);
  }
}

game(); // invoke the game 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

Implement horizontal scrolling feature to code container

One cool feature on my blog is the codebox where I can insert snippets of HTML, CSS, and Javascript codes. Here's an example of how my CSS code looks: .post blockquote { background-image: url("https://dl.dropbox.com/u/76401970/All%20Blogger%20Tr ...

"Learn how to clear an input field using jQuery with this simple guide

I've gone through a few discussions, such as this one and that one, but I'm still struggling to clear the input field after submission. What is the simplest way to achieve this? This is my current approach: $(document).ready(function(){ $(& ...

Finding the average JSON value using d3.js

Here is the structure of a JSON file I am working with: [ {"id":1,"sex":"Female","programming":5, "project":7}, {"id":2,"sex":"Male","programming":8, "project":4}, {"id":3,"sex":"Female","programming":5, "project":6}, {"id":4,"sex":"Male","programm ...

Tips on Including Static Header and Footer in Multiple HTML Pages

What is the best way to reuse a header and footer on multiple HTML pages without repeating code? I have 5 HTML pages that all need to include the same header and footer elements. How can I efficiently reuse these components across all pages? ...

Experiencing an overflow of redirects in PHP contact form

I am encountering an issue on my website where there are too many redirects occurring when attempting to submit a form that is supposed to be sent via email. The connection between the form and email seems to be correct. Form Code: <section class=" ...

The vanishing HTML Div with a fixed height

After implementing a navigation bar inside my header container, I noticed that the main_image div with a blue background color disappeared. Despite setting a height for it, the div was nowhere to be seen. Additionally, the welcome_text div seemed to lose i ...

Exploring the World with AngularJS and Google Maps API through ngGeolocation

Having some difficulty displaying my geolocation on Google Maps API using a marker. I am utilizing the ng controller ngGeolocation and the http://angular-ui.github.io/angular-google-maps/ Previously, I hardcoded the marker and map location without any is ...

I'm currently working on a course assignment and I've encountered an issue where nothing happens when I try to execute node

Having trouble with the readline for input execution. Any helpful hints or tips? I've been using it in the same file for all exercises, checked stackoverflow too but realized I'm on Windows. This is my code const { rejects } = require('asse ...

Adding a promise to an array using Javascript

I am facing an issue while attempting to create an array of promises and then calling them using Promise.all. The problem lies in correctly pushing the functions into the array. It seems like they are getting executed instead of being inserted and waiting ...

The div has extra white space at the bottom due to the Hide/Show content feature

Having trouble stretching a scrolling div to 100% of its parent container's height? The Hide/Show content feature is causing whitespace at the bottom of the div. Check out the jsfiddle here: http://jsfiddle.net/fkvftff2/1/ LATEST UPDATE: The issue a ...

Issue with $.ajax({}) causing Express Session to fail saving

I'm facing an issue where I am trying to store data in an Express session, but it seems that Express is treating each AJAX request as a new session and not saving my data consistently. Here's the client-side code: $.ajax({ url: '/orders& ...

Experiencing Strange Issues with Jquery Image Carousel... Assistance Needed!

I recently created a jquery slideshow using a tutorial I found at this link: While the slideshow is functioning correctly for the most part, there is a strange issue that occurs right at the beginning when displaying the first image. Initially, the first ...

The process of loading an image becomes stuck once the submit button is pressed

I have multiple JSP pages where I use an ajax call to submit data. On these pages, I am able to display a loading image before the ajax call and hide it once the call is complete, which works perfectly. $(document).ajaxComplete(function() { $("#loadi ...

After changing the value of a <select> element in Vue, the fetched data is delayed by one step

I'm currently working on a feature that involves fetching data from a URL that changes every time a user chooses a new value from a <select> dropdown. The fetched data updates the songkickData array with the latest information. However, when I c ...

Transferring data between AngularJS and non-AngularJS environments

Within my AngularJS application, the $scope.mydata variable holds some important data within a controller. I am currently working on a regular JSP page without any AngularJS functionality, but I need to access the data stored in the scope variable (mydat ...

Responsive design parameters

After creating a media query specifically for phones, I realized that I needed one for desktop as well. @media screen and (max-device-width: 480px), screen and (max-width: 480px) { ...css here... body {width:50%;} However, when I attempted to add a sim ...

What causes the inconsistency in TypeScript's structure typing?

It is well-known that TypeScript applies structure typing, as demonstrated in the following example: interface Vector { x: number; y: number; } interface NamedVector { x: number; y: number; name: string; } function calculateLength(v: Vecto ...

Optimizing NodeJS for scheduling and sending bulk text messages based on MongoDB data

I am currently developing an application that relies on MongoDB database entries to send text messages through AWS. The information stored in the database includes the message content, phone number, and scheduled time for sending the message. As of now, ...

Integrate a new Webview Window into an existing iOS App to display locally stored HTML content

Integrate a WebView Window into an existing iOS application to display locally stored HTML content. I have already completed the feed RSS feature in my app, but now there is a requirement for a section that can be easily updated... ...

What is the best way to enter text into the terminal following the execution of "yarn start"?

While developing a Node chat application, I encountered an issue where I am unable to type anything in the terminal after entering "yarn start". The tutorial I am following shows that the instructor can still input commands in their terminal after running ...