Revise a button using JavaScript

Hey there, I could really use some assistance. Currently, I am learning Javascript as a part of a project I am working on and I seem to have run into a bit of an issue with updating the display status of a button on my webpage.

I am trying to set up a condition where a button appears or disappears based on whether a certain condition is met.

I have two buttons that should each be clicked a specific number of times (let's say 12 and 13). I have managed to create a condition where if button1 == 12 && button2 == 13, then change the button status to block instead of hidden. However, once this condition is met, if I click either button again, the button that should appear after the condition stays visible even though the condition is no longer true.

//var clickNeeded = 12;
var clicks = 0;
var clicks1 = 0;


function countDown() {
    clicks += 1;
    document.getElementById("test").innerHTML = clicks;
    if (clicks == 12 && clicks1 == 13){
        document.getElementById("step1").style.display = 'block';
    }
};
function countDown1() {
    clicks1 += 1;
    document.getElementById("test1").innerHTML = clicks1;
    if (clicks == 12 && clicks1 == 13){
        document.getElementById("step1").style.display = 'block';
    }
};

if (clicks != 12 && clicks1 != 13){
    document.getElementById("step1").style.display = 'hidden';
}



function messageAfficher() {
    document.getElementById("enigme").style.display = 'block';
}
body{
    background-color: black; 
    
}

@font-face{
    font-family: 'hacked';
    src: url(font/Hacked-KerX.ttf);
    font-style: normal;
}

.header{
    text-align: center;
    margin: 50px 100px;
    font-family: hacked;
}

.header h1{
    color: purple;
    font-size: 80px;
    margin: 50px    
}

.header p{
    color: purple;
    font-size: 20px;
    text-align: justify;
    padding-right: 100px;
    padding-left: 100px; 
}

.enigme {
    color: aliceblue;
    text-align: center;
    font-family: hacked;
}

.step {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 50px;
}
<!DOCTYPE html>
<html>  
    <head>
        <meta charset="utf-8">
        <script src="fonction.js"></script> 
        <title>Escape Game</title>
        <link rel="stylesheet" href="main.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>
<!--===========================================================================================================================-->
    <body>
        
        <div class="header">
            <h1>Welcome to this adventure!</h1>
            <p>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt...
            </p>
        </div>
        
        <div class="step">
            <button id="test" onclick="countDown()">0</button>
        </div>
        <div class="step">
            <button id="test1" onclick="countDown1()">0</button>
        </div>
        <div class="step">
            <button id="step1" onclick="messageAfficher()" style="display:none">Where am I?</button>
        </div>
        <div class="enigme">
            <p id="enigme" style="display:none">Coordinates</p>
        </div>
        
    </body>
<!--===========================================================================================================================--> 
</html>

I've tried adding an If condition after my function, but it doesn't seem to work, which makes sense, given that it's not quite logical. So, I'm a bit stuck here ^^'
Thanks in advance! :D

Answer №1

Make sure to set the display property to none instead of using hidden.

If you are using hidden, it should be combined with visibility.

Additionally, remember to include an else condition to hide the step1 element properly. Currently, it is placed outside and may not work as expected when clicking the buttons.


function countDown() {
    clicks += 1;
    document.getElementById("test").innerHTML = clicks;
    if (clicks === 12 && clicks1 === 13){
        document.getElementById("step1").style.display = 'block';
    } else {
        document.getElementById("step1").style.display = 'none';
    }
}

function countDown1() {
    clicks1 += 1;
    document.getElementById("test1").innerHTML = clicks1;
    if (clicks === 12 && clicks1 === 13){
        document.getElementById("step1").style.display = 'block';
    } else {
        document.getElementById("step1").style.display = 'none';
    }
}

Consider abstracting the repeated code into a separate function for reusability. Use strict comparison === instead of loose comparison ==.


function countDown() {
    clicks += 1;
    document.getElementById("test").innerHTML = clicks;
    hiddenOrVisible(clicks, clicks1);
}

function countDown1() {
    clicks1 += 1;
    document.getElementById("test1").innerHTML = clicks1;
    hiddenOrVisible(clicks, clicks1);
}

function hiddenOrVisible(clicks, clicks1) {
    if (clicks === 12 && clicks1 === 13) {
        document.getElementById("step1").style.display = 'block';
    } else {
        document.getElementById("step1").style.display = 'none';
    }
}

Answer №2

To simplify your code, you can move the logic for hiding the button into the click handling function.

//var clickNeeded = 12;
let clicksOne = 0;
let clicksTwo = 0;


function countDown(id) {
    const buttonClicks = id === 'test1' ? ++clicksOne : ++clicksTwo;
    document.getElementById(id).innerHTML = buttonClicks;
    if (clicksOne == 12 && clicksTwo == 13){
        document.getElementById("step1").style.display = 'block';
    } else {
      document.getElementById("step1").style.display = 'none';
    }
};

function messageAfficher() {
    document.getElementById("enigme").style.display = 'block';
}
body{
    background-color: black; 
    
}

@font-face{
    font-family: 'hacked';
    src: url(font/Hacked-KerX.ttf);
    font-style: normal;
}

.header{
    text-align: center;
    margin: 50px 100px;
    font-family: hacked;
}

.header h1{
    color: purple;
    font-size: 80px;
    margin: 50px    
}

.header p{
    color: purple;
    font-size: 20px;
    text-align: justify;
    padding-right: 100px;
    padding-left: 100px; 
}

.enigme {
	color: aliceblue;
	text-align: center;
	font-family: hacked;
}

.step {
	display: flex;
	justify-content: center;
	align-items: center;
	height: 50px;
}
<!DOCTYPE html>
<html>  
    <head>
        <meta charset="utf-8">
        <script src="fonction.js"></script> 
        <title>Escape Game</title>
        <link rel="stylesheet" href="main.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    </head>
<!--===========================================================================================================================-->
    <body>
        
        <div class="header">
            <h1>Welcome to this adventure!</h1>
            <p>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.<br>
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
            </p>
        </div>
        
        <div class="step">
            <button id="test1" onclick="countDown(this.id)">0</button>
        </div>
        <div class="step">
            <button id="test2" onclick="countDown(this.id)">0</button>
        </div>
        <div class="step">
            <button id="step1" onclick="messageAfficher()" style="display:none">Where am I?</button>
        </div>
        <div class="enigme">
            <p id="enigme" style="display:none">Coordinates</p>
        </div>
        
    </body>
<!--===========================================================================================================================--> 
</html>

Answer №3

Here are a couple of important things to note:

  1. Remember to verify the count condition each time you click on a button.

  2. The value hidden is not valid for the display property; make sure to use none instead.

I recommend avoiding repetitive code in multiple locations. These are the necessary changes that should be made:

//var clickNeeded = 12;
var clicks = 0;
var clicks1 = 0;

function checkCondition(){
   if (clicks != 12 && clicks1 != 13){
     document.getElementById("step1").style.display = 'none';
   }
   else if (clicks == 12 && clicks1 == 13){
     document.getElementById("step1").style.display = 'block';
   }
}

function countDown() {
    clicks += 1;
    document.getElementById("test").innerHTML = clicks;
    checkCondition();
}

function countDown1() {
    clicks1 += 1;
    document.getElementById("test1").innerHTML = clicks1;
    checkCondition();
};

function messageAfficher() {
    document.getElementById("enigme").style.display = 'block';
}

Answer №4

Streamlined your code and adjusted the click count to 5, while ensuring it still functions as intended: Users can click on both buttons up to a specified amount of times before revealing a hidden button with an additional click.

const btns=[...document.querySelectorAll('[id^=test]')];
function showElement(id){document.querySelector('#'+id).style.display='block'}
var maxClicks=5;
document.querySelector('.buttons').addEventListener('click',function(ev){
  var b=ev.target;
  if (b.id)
    if (b.id.substr(0,4)=='test') {
      if (b.textContent<maxClicks) b.textContent=+b.textContent+1
      else if(btns.reduce((s,v)=>+v.textContent+s,0)==2*maxClicks)
        showElement('step1')
    } else if (b.id=="step1") showElement('enigme')
})
#step1, #enigme {display:none}
<div class="header">
  <h1>Welcome to this adventure!</h1>
  <p>Some brief irrelevant text.</p>
</div>
<div class="buttons">
<div class="step"><button id="test">0</button></div>
<div class="step"><button id="test1">0</button></div>
<div class="step"><button id="step1">Where am I?</button></div>
<div class="enigme">
  <p id="enigme">Coordinates</p>
</div>
</div>

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

encountering a problem while trying to run `npm install react-native-modal-datetime-picker` in the terminal

I've encountered an issue while working on my app where I keep getting errors when trying to install the react-native-modal-datetime-picker package, as well as other date time picker packages like @react-native-community/datetime-picker The specific ...

Having trouble bringing a 3D object into ThreeJS?

Encountering difficulties while trying to load a 3D object into Three.JS on my website. The 3D images were created in Blender and then exported to .JSON format using MrDoobs exporter addon. edit: This is the exporter I am utilizing - https://github.com/mr ...

Learn how to incorporate a HTML page into a DIV by selecting an Li element within a menu using the command 'include('menu.html')'

I have a website with both 'guest' and 'user' content. To handle the different menus for logged-in and logged-out users, I created menuIn.html and menuOut.html files. These menus are included in my MainPage.php using PHP logic as sugges ...

Unable to set maximum width for images in Firefox browser

Welcome to my page where I am utilizing the latest version of Bootstrap v3.2.0 I have encountered an issue when using the display: table-cell; CSS property within a div block. Specifically, the max-width: 100%; CSS property does not function as expected f ...

Creating a many-to-many relationship in Sequelize using a join table to insert data

I recently set up two models in sequelize with a many-to-many relationship. While Sequelize successfully created the join table, I am facing difficulties when trying to insert data into it. Despite going through the documentation section on associations ...

How can AJAX be utilized with both file and text inputs?

I have a basic form enclosed in a modal window, dynamically generated using jQuery: <form name="altEditor-form" id="altEditor-form" enctype="multipart/form-data" role="form"> <div class="form-group"> <div class="col-sm-5 col-md- ...

Tips for adjusting the border color of a MUI Select field

https://i.stack.imgur.com/rQOdg.png This MUI select box changes color from blue to black based on selection. The challenge is to customize the text and border color to white (currently set as blue). Any suggestions on how to achieve this? ...

Guide to Monitoring Object Property in a Vue Extension

Introduction Let's look at a basic plugin setup: import SomeObject from "./SomeObject"; /** * Simple Plugin Example... */ export default { install(Vue){ Vue.prototype.$someObject = Vue.observable(SomeObject); } } The g ...

Decide whether Variable Name is equal to the String

I am currently facing an issue. var myArrayVariable1 = new Array(); var myStringVariable1 = 'myArrayVariable1'; var myStringVariable2 = 'myArrayVariable2'; Is there a way to determine if one of the strings matches the variable name? F ...

Jest's expect.any(Object) function is not able to match CancelToken

After converting some files in a project to TypeScript, I encountered a test failure related to the following code: expect(mocks.request).toHaveBeenCalledWith({ headers: { 'Content-Type': 'bar' }, method: 'put', params: ...

nw.js sending a multipart/form-data request

I am looking to send POST data to a server from nw.js. The data consists of simple name-value pairs and one file, meaning that the request type will be multipart/form-data. All the data needs to be sent in one single request. To do this, I have been using ...

Sending arguments enclosed in double quotation marks

Having an issue while trying to pass a variable with the character ", especially when dealing with "Big Bang". <?php echo $aux; //Hi! "Text" Text2'Text3 ?> //mysql_real_escape_string($aux); addslashes($aux); //output Hi! \"Big Bang&bso ...

Save JavaScript console output to a log file using Firefox

We are currently utilizing a web application that operates in kiosk mode using Firefox with the RKiosk extension. A potential issue we've encountered is a rare JavaScript error within the system. Unfortunately, due to the inability to access the JavaS ...

The document.write function causes the page to break

I have created a view that loads another view asynchronously and then replaces the current one using document.write (yes, I want to replace the whole page!): $.ajax({ type: "GET", url: myUrl, data: null, async: true, success: function (result) { ...

Exploring deep nested writes within Prisma

Describing my database schema: model User { id Int @default(autoincrement()) @id createdAt DateTime @default(now()) email String @unique role String @default("user") sessions Sessio ...

Extracting all href links from the webpage source code utilizing Selenium WebDriver in Java

Currently, I am working on testing the HTTP RESPONSE of all the href links present on a webpage. My approach involves using WebDriver to fetch all links from the page and then utilizing http.connect to obtain the response status. Here is a snippet of the ...

search for the compose function in the material table within a react component

When I receive a string array as a response from the API for lookup, it looks like this: ['India', 'Sri Lanka'] I am looking to pass this as a parameter to a Material React table column as a List of Values (LOV) in the following format ...

The interaction between a JavaScript function call and C# is not functioning properly

Attempting to invoke the JavaScript function from CodeBehind ( C# ) : function scrollToBottom() { window.scrollTo(0, document.body.scrollHeight); } The function successfully executes when directly called from my asp.net application. However, ...

"All my online spaces are chaotic and cluttered beyond belief, overflowing with content in high-definition

One issue that frequently arises for me when developing websites is related to media queries and resolution. I have utilized the following code using a max-width of 1920px: @media only screen and (max-width : 1920px) {} However, I am facing challenges in ...

What's causing margin-top to be reversed while margin-bottom remains stationary?

I have encountered a specific issue that I can't seem to find a solution for. I am attempting to include the text "2017 Indie" at the bottom of the page. When I apply margin-top to a pixel value, the text remains unchanged and nothing happens. However ...