The Gusser Game does not refresh the page upon reaching Game Over

Hi there, I am a beginner in the world of JavaScript and currently working on developing a small guessing game app. However, I have encountered an issue where the page is not reloading after the game is over and the 'Play Again' button appears to be disabled instead of triggering a reload.

I would greatly appreciate your assistance with this problem as I have been unable to resolve it on my own.

let min = 1, max = 10, winnerNum = RandNum(max,min), gussNum = 3;

// UI variables

let game = document.querySelector('#game'),
    minNum = document.querySelector('.min-num'),
    maxNum = document.querySelector('.max-num'),
    gussBtn = document.querySelector('#gussBtn'),
    gussInput = document.querySelector('#input'),
    message = document.querySelector('.msg');

// assigning min and max values

minNum.textContent = min;
maxNum.textContent = max;

// reload the game upon button click

game.addEventListener('mousedown', function(e){
    if(e.target.className ==='play-again'){
        window.location.reload();
        // Why isn't the page being reloaded??
    }
});

// listening for guessed number input

gussBtn.addEventListener('click', function(){
    let guss = parseInt(gussInput.value);
    console.log(guss);

    // validate user input

    if(guss===winnerNum){
        gameOver(true,`Winner Winner Chicken Dinner, Yes ${winnerNum} is the correct number`)
    } else{
        gussNum -= 1;

        if(gussNum===0){
            gameOver(false,`You lost game over, the correct number is ${winnerNum}`)
        } else if(gussNum<0){
            gussBtn.disabled=true;
            gussInput.disabled=true;
        } else {
            gussInput.disabled=true;
            gussInput.style.borderColor = 'red';
            gussInput.value = '';
            setMessage(`You have ${gussNum} left!`, 'red')
        }
    }
});

function gameOver(won,msg){
    let color;
    won === true ? color = 'green' : color='red';
    gussInput.disabled=true;
    gussInput.style.borderColor = color;
    // gussBtn.disabled=true;
    setMessage(msg, color);
    gussBtn.value='Play Again';
    gussBtn.classList.add('play-again');
}

function RandNum(max,min) {
    return Math.floor(Math.random()*(max-min+1)-min);
}

function setMessage(msg, color) {
    message.textContent = msg;
    message.style.color = color;
}

HTML Section

<body>
<div class="container">
<div class="row">
    <div class="col-md-6 mx-auto">
        <div class="card card-body text-center mt-5">
            <h1 class="heading display-5 pb-3">Game Gusser</h1>
            <p>Guess a number between <span class="min-num"></span> and <span class="max-num"></span></p>
                <div class="form-group" id="game">
                    <div class="input-group">
                        <input type="number" class="form-control" id="input" placeholder="Enter your guess...">
                        <input type="submit" class="btn btn-dark btn-block mt-4" id="gussBtn">
                    </div>
                    <p class="msg mt-4"></p>
                </div>
        </div>            
    </div>
</div>
</div>

<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>
<script src="js/bootstrap.min.js"></script>
<script src="js/app.js"></script>
</body>

The desired outcome is for the Play Again button to trigger a page reload so that users can enjoy playing the game again seamlessly.

Answer №1

There is a possibility that the className may not be exactly 'play-again'.
Why not just use a 'click' event instead?

function hasClass ( elem , klass ) {
    return (" " + elem.className + " " ).indexOf( " " + klass + " " ) > -1
}; 

let game = document.getElementById('game');
game.addEventListener('click', function(e){
    if (hasClass(e.target , 'play-again')){
        window.location.reload();
    }
});

I would also advise against using location.reload(). It can result in a poor user experience. Perhaps consider rerunning the script that initializes the game instead?

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

Navigating with Angular: Understanding ng-view and Routing

How does Angular understand which template view to request containing the 'ng-view' element? If I directly navigate within my application to http://localhost/Categories/List/accessories , a request is still sent to '/' or the index ...

Take charge of Bootstrap 4 dropdown transformation class while creating a Megamenu

I am currently working on creating a Megamenu using Bootstrap 4's dropdown Component. The issue I'm facing is related to Javascript adding CSS styles with transform, such as transform: translate3d(9px, 5px, 0px); This is causing disruption in m ...

Tips for updating iframe source without refreshing the iframe?

I am facing an issue with two frames where I need to copy the content from the first frame (myframe) to the second frame (myframe2) using JavaScript. The challenge is that when I set the "src" attribute for myframe2, it causes a reload of FrameSecond. Is ...

Retrieving a database value in Node.js Firestore containing a space

Hello, I'm just getting started with node Js and I anticipate that it will be a smooth ride! Currently working on an application using node JS with Firestore where I need to retrieve data like "display name": James and "Age": 22 Since Age does not h ...

Using a variable to contain a loop in Jquery

Seeking assistance with a jQuery function that retrieves values from a PHP form to create a variable for an ajax call. Is it possible to include a loop within a variable? Below is a snippet of my code to provide better context: ... var teacher_ids = $( & ...

Using $nin alongside $and in Mongoose

Implementing a filter for an admin user using mongoose operations. The user should be able to view all saved files except for those that are classified as draft files. However, the admin user should still have access to their own saved draft files. Code ...

Troubleshooting the NullInjectorError in Angular - Service Provider Missing?

I'm facing an issue in my code where I have buttons that should trigger pop-ups displaying details as a list when clicked. However, every time I click the buttons, I encounter the error mentioned below. It seems like I am unable to access the desired ...

What is the best way to prevent a window from opening when the required form fields are left blank?

Currently, I have a submit button on my form that triggers a jQuery function to open a window based on the user's selection. However, I only want the window to open if all the necessary fields are filled out. I have the existing code for this function ...

Problem with AWS Lambda function handler failing to insert data into Athena

Trying out a sample code snippet for Amazon Athena to test data insertion, but it's not working as expected. The CloudWatch logs don't show any output after the statement execution is completed. Even when switching to a simple select statement, t ...

Manipulating HTML content with Javascript Array

Is there a way to retain Javascript context from an array? Any suggestions for improving this code? SAMPLE: <html> <script type="text/javascript"> var rand = Math.floor(Math.random() * 6) + 1; var i = Math.floor(Math.random() * 6) + 1; var ...

TypeScript/Javascript - Error: The specified function is not callable

After recently delving into TypeScript, I found myself encountering an error in my code for a wheel mini-game on my app. The specific error being displayed in the console is: this.easeOut is not a function The relevant portion of the code causing the iss ...

Activate every switch using only one switch

Below is the table I am working with. I'm trying to toggle all switches with the class name the-checkbox-input when the first switch with the class name checkbox-input-main is toggled. The code snippet I have tried doesn't seem to be working, ev ...

Finding the smallest value for each day in MongoDB using Mongoose

I have a collection in my MongoDB database called measured_data that includes entries for each day containing the fields measured_at and value. I am looking for a way to use Mongoose to find the lowest value recorded for each day. Any insights or suggest ...

A duo of adjacent buttons styled with HTML, CSS, and Bootstrap

I'm encountering an issue with the layout of my design. On my product page, I have two buttons placed on top of each other because one is within a form (refer to the image). https://i.sstatic.net/cS9TI.jpg I would like to position the two buttons s ...

Creating a React component that allows for pagination using data fetched from a

I have a Spring Boot endpoint that retrieves and lists items from a database: @RequestMapping(method = RequestMethod.GET, value = "/task", produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<?> processTask(@Valid TaskSearchP ...

changing button text in ajax upon successful completion

I am looking to update the button text upon successful completion. Specifically, I would like to change it to "accepted" after a successful response. <button type="button" onclick="saveData<?php echo $row1->id; ?>()">Accept</button> ...

The message "Error: Unknown custom element: <router-view> - have you properly registered the component?" is prompting for a solution

Even though the name is correctly capitalized in all my component instances, I am still encountering an error. After researching similar issues online, it appears that the problem usually revolves around naming discrepancies. However, I have double-checked ...

The use of p-message in Angular's PrimeNg library is not permitted

Hey there, I'm having a bit of trouble with the p-message Tag in Angular. I believe I've imported it correctly as shown below. import { MessageModule } from 'primeng/message'; imports: [ .... MessageModule, ... In the ...

waiting for elements in Nightwatch.js using FluentWait

I am seeking assistance on implementing FluentWait using nightwatch.js. How can I achieve this? Within my project, I have a global.js file that includes: waitForConditionPollInterval : 300, waitForConditionTimeout : 5000, However, it seems like this ...

What steps can I take to address a 500 internal server error when attempting to execute a Python script within a CGI file?

Looking to execute a python script on a Strato-hosted website (.nl) using a CGI file. The setup includes my code: a cgi file, python file, and dependencies file for adding something to the PATH. Check out the files here. Here's what the folders look ...