Preventing a Click Event from Firing in JavaScript DOM

Is there a way to deactivate my buttons once a certain condition is met? Whenever the score reaches 5 on either side, the game just keeps going without displaying the final score. I attempted using a while loop, but it caused crashes. Is there a simple method similar to jQuery for disabling the buttons?

const rock = document.querySelector('.rock');
const paper = document.querySelector('.paper');
const scissors = document.querySelector('.scissors');
const h3 = document.querySelector('h3');
const pscore = document.querySelector('#pscore');
const cscore = document.querySelector('#cscore');
let computerScore = 0;
let playerScore = 0;

function computerPlay() {
    var choice = Math.floor(Math.random() * 3 ) + 1; //generate a number 1-3 to find computer choice
    if(choice == 1) {
        return 'rock';
    }
    else if(choice == 2) {
        return 'paper';
    }
    else {
        return 'scissors'

    }
} 

let result; // Is there a simpler way to write this code?

    rock.addEventListener('click', () => {
        if(computerPlay() == 'rock') {
            result = `The computer chose rock and you chose rock! It's a tie! No change in score.`;
            h3.textContent = result;
            
        }
        else if(computerPlay() == 'paper') {
            result = `The computer chose paper and you chose rock! You lose! Computer Score +1!`;
            h3.textContent = result;
            computerScore++;
            cscore.textContent = computerScore;

     
        }
        else {
            result = `The computer chose scissors and you chose rock! You win! Player Score +1!`; 
            h3.textContent = result;
            playerScore++;
            pscore.textContent = playerScore;

        }
    });

    let playerPaper = paper.addEventListener('click', () => {
        if(computerPlay() == 'paper') {
            result = `The computer chose paper and you chose paper! It's a tie!`;
            h3.textContent = result;    
        }
        else if(computerPlay() == 'scissors') {
            result = `The computer chose scissors and you chose paper! You lose!`;
            h3.textContent = result;
            computerScore++;
            cscore.textContent = computerScore;
        }
        else {
            result = `The computer chose rock and you chose paper! You win!`; 
            h3.textContent = result;
            playerScore++;
            pscore.textContent = playerScore;
        }
        
    });

    let playerScissors = scissors.addEventListener('click', () => {
        if(computerPlay() == 'scissors') {
            result = `The computer chose scissors and you chose scissors! It's a tie!`;
            h3.textContent = result;    
        }
        else if(computerPlay() == 'rock') {
            result = `The computer chose rock and you chose scissors! You lose!`;
            h3.textContent = result;
            computerScore++;
            cscore.textContent = computerScore;
        }
        else {
            result = `The computer chose paper and you chose scissors! You win!`; 
            h3.textContent = result;
            playerScore++;
            pscore.textContent = playerScore;
        }
    })

function playGame(computerChoice) {
    computerChoice = computerPlay();
    if(playerScore == 5) {
        h3.textContent = `The score is 5 to ${computerScore}! You win!`;
    }
    else if(computerScore == 5) {
        h3.textContent = `The score is 5 to ${playerScore}! The computer wins!`;
    }
    
}

The functionality works smoothly except for the 'end game' feature. Any help or feedback would be greatly appreciated!

Answer №1

Ways to Deactivate a "Click" Event

The feedback in the comments provides some clever suggestions for enhancing your game. It might be beneficial to explore those ideas. However, if you are interested in disabling click events, there are various approaches you can take.

1. Implement a disabled attribute on your button.

window.onload = () => {
  const button = document.getElementById("myClicker")
  button.disabled = true
}
<button id="myClicker">Click</button>

2. Apply the CSS property pointer-events: none;

window.onload = () => {
  const button = document.getElementById("myClicker")
  button.addEventListener("click",function(){console.log("hi")})
  button.style.pointerEvents = "none";
}
<button id="myClicker">Click</button>

The second method is suitable when informing the user that the button is inactive is unnecessary.

3. Use Prevent Default event.

window.onload = () => {
  const button = document.getElementById("myClicker")
  button.addEventListener("click",function(e){
    e.preventDefault;
  })
}
<button id="myClicker">Click</button>

4. Eliminate Event listener.

document.getElementById("yourButtonId").removeEventListener("Click", yourFunctinoNameHere);

Answer №2

Greetings to Charles. It seems that, as mentioned by @StackSlave, repeatedly calling the computerPlay() function may lead to skewed results, potentially favoring the final else condition in each button scenario. While this is a logical error, the program will still execute.

Your implementation involves extensive functionality within onclick events, with little consideration for an enable indicator. To address this, I have split the program into two components:

  1. Round
  2. Ui

The Round component manages user and computer selections, along with scoring updates. On the other hand, the Ui component handles button interactions for making choices during a round, displaying outputs, updating scores, and potentially ending the game. Additionally, there's a feature to reset the game in the Ui, allowing for a fresh start. Notably, I've organized these functionalities into objects instead of standalone functions to facilitate tracking states. Furthermore, it might be beneficial to provide constants such as rock, paper, player score, etc., directly to the Ui constructor rather than relying on global variables.

const rock = document.querySelector(".rock");
const paper = document.querySelector(".paper");
const scissors = document.querySelector(".scissors");
const h3 = document.querySelector("h3");
const pscore = document.querySelector("#pscore");
const cscore = document.querySelector("#cscore");

const NO_SELECTION = -1;
const SELECT_ROCK = 0;
const SELECT_PAPER = 1;
const SELECT_SCISSORS = 2;

class Round {
  constructor() {
    this.playerChoice = NO_SELECTION;
    this.computerChoice = NO_SELECTION;
  }

  // Rest of the methods from the original code goes here
}

class Ui {
  // Constructor and other methods from the original code can be added here
}

// Initializing the game interface
const gameInterface = new Ui();

Answer №3

I prefer not to disable anything, but rather add and remove classes as needed. Take a look at this simple game of RockPaperScissors that I've created. There's a neat little library included above the line that says // magic under here. You might pick up some tips from it:

//<![CDATA[
/* js/external.js */
// Code for RockPaperScissors game goes here
]]>
*{
  /* CSS code for styling elements goes here */
}
<!DOCTYPE html>
<html>
  <head>
    <meta charset='UTF-8' /><meta name='viewport' content='width=device-width, height=device-height, initial-scale=1, user-scalable=no' />
    <title>Rock, Paper, Scissors</title>
    <link type='text/css' rel='stylesheet' href='css/external.css' />
    <script src='js/external.js'></script>
  </head>
<body>
  // HTML structure for the game interface goes here
</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

cannot display static css files in an express jade template

Looking for a solution to the issue with the dollar answer (same problem). I have app.coffee: pp.configure -> publicDir = "#{__dirname}/public" app.set "views", viewsDir app.set "view engine", "jade" app.use(stylus.middleware debug: true, src: view ...

JavaScript resets the timer whenever the page is refreshed

Is there a way to maintain the timer in a quiz even after refreshing the page? <html><h1>Js Timer</h1> <div style="font-weight: bold;" id="quiz-time-left"></div> <script type="text/javascript"> var total_seconds = ...

Employ a variable in order to send json

Is it possible to insert data into a predefined JSON variable using a variable? Here are the predefined JSON variables: data(){ return { dataMON: [], dataTUE: [], dataWED: [], dataTHU: [], ...

Material UI Grid Items not stretching to fill the entire available width

I'm currently working with a nested Grid system in Material UI, but the Grid items are only occupying a fixed width and leaving some empty space. The issue arises when this fixed space is used up and instead of adjusting their internal free space, the ...

Load data onto a webpage using Jquery or json without the need to refresh the page, seamlessly integrate it

After receiving data on an html/php page from the database, I often find myself needing to edit it. However, I wish for this data to update automatically without the need to refresh the page each time I make changes and click the submit button. I've c ...

What is the most efficient way to use a for loop with JavaScript querySelectorAll to move multiple images?

I'm trying to move multiple images by defining each one with a for loop. Below is the code I have: var elem = document.querySelectorAll(".yikama"); var el; for (i = 0; i < elem.length; i++) { var el = elem[i] el.addEventListener(& ...

Webpack automatically prepends "auto/" to script tags in the compiled HTML file

I am currently setting up an application for coding, but I am facing a problem with webpack. Every time I build the application, webpack automatically adds "auto/file.js" to the script tags instead of just "file.js". I have checked all my webpack configura ...

Leverage PHP to retrieve information from a JSON file and integrate it into a dropdown menu on an HTML

I've been given a task to develop a PHP routine that will extract the ISO code and name from a geojson file for use in a dropdown list of countries on a website. This is completely new to me and I'm finding it difficult to understand the documen ...

What is the process for customizing the color of the focused label in Material UI through styling?

Recently, I delved into the world of JSS for styling and ran into an intriguing issue. My goal was to modify the color of a label in an InputLabel component when it is in focus state. After some tinkering, I managed to achieve this using the code snippet b ...

Having trouble with Chrome not setting cookies in a MERN stack application?

I've been attempting to save a JWT token in a cookie using node.js, but for some reason it's not getting set in the browser. Even after logging the variable responsible for setting the cookie and seeing that it indicates the cookie is saved, it s ...

Create a typing effect in Javascript that mimics the user's input

Trying to simulate a typing effect with the sentence extracted from user input using JavaScript, but encountering some issues. Successfully capturing and displaying the input in the console with console.log(), however, incorporating the typing effect func ...

What are the time-saving benefits of utilizing semantic X/HTML in CSS development?

Exploring the Time-Saving Power of Semantic X/HTML Markup - Streamlining CSS writing for websites Adapting to future design changes from clients with ease Avoiding the time-consuming nature of Table-based layouts in all scenarios Today, I have the task ...

Using the combination of z-index and visibility:hidden makes the button go completely undetect

Can someone please review this code? .parent { visibility: hidden; position: relative; z-index: 1; } .child { visibility: visible; } <button class="parent"> <span class="child">content</span> </button> I' ...

How to vertically align content within a custom div container using Bootstrap 4

I have been searching for answers to my specific case, but I haven't found any that suit my needs. My goal is to create a translucent background within a Bootstrap container to enhance the readability of text. The result I was able to achieve so far ...

When attempting to pass data to a modal, an error occurs due to props being undefined. This results in a TypeError with the message "Cannot

I'm working on a product listing feature where each item displays some information along with a "more details" button. When the button is clicked, a modal window opens to show additional details of the specific product (using props to pass data betwee ...

When the toggle enabled div is clicked, the drag event is triggered

My draggable div has a "splitter" for expanding and collapsing, but it should only do so on double click or drag. However, when I single click the splitter while the div is collapsed, it repositions to around 10px width. I've attempted using 'st ...

How can I stop Html.ListBoxFor from truncating the overflow text of the selected item?

I am facing an issue with a list of phone accessories where the combination of material number and name is too long, causing it to exceed the width of the listbox (Html.ListBoxFor). My solution was to add horizontal scroll to the list by using the overflo ...

What determines the priority of execution in the execution context stack?

Check out this insightful tutorial on execution context in JavaScript here. It's interesting how the order of invoking functionA() and console.log("GlobalContext") differs in terms of writing code versus the execution context stack. I'm curious, ...

Display information from an array in checkboxes. If the same data appears in another array, the corresponding checkbox in React will be automatically checked

I currently have two arrays. The first array, let's call it arr1, contains multiple objects such as [{"Name":"Mr.X"},{"Name":"Mr.Y"},{"Name":"Mr.Z"}]. The second array, named arr2, holds a few values like [{"Name":"Mr.Z"}]. My goal is to display all ...

how to quietly change the focus of an element using jquery and css?

Whenever I modify the CSS of a scrolled-past element, the view abruptly jumps to that particular div (by scrolling up) upon applying CSS changes using .css(...). Something as simple as adjusting the background-color can trigger this effect. Is there a wor ...