Automatically update button appearance upon reaching zero value using JavaScript

Whenever I click the button, the user's HP decreases until it reaches 0 and then the button changes. However, a peculiar issue arises when the userHealth hits zero - the button does not change immediately. An additional click is required for the button to update. How can this be resolved?

JavaScript:

$(".attBtn").click(function() {

    var userId = 4;
    var attackdmg = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
    var userdmg = Math.floor(Math.random() * (20 - 1 + 1)) + 1;
    var minimum = 0;    

    if(userHealth == 0){
        info.innerHTML = '<strong>'+user.textContent+'</strong> have been defeated.';
        attackBtn.css("backgroundColor", "blue");
        attackBtn.css("border", "none");
        innerAttBtn.innerHTML = "Get the reward <img src="+"/img/chest2.png"+"/> ";
        return false;           
    }else if(attackerHealth == 0){
        info.innerHTML = '<strong>You</strong> have been defeated.';
    }else if(attackerHealth == 0 && userHealth == 0){
        info.innerHTML = '<strong>DRAW FIGHT</strong>';
    }else{

    userHealth -= attackdmg;
    attackerHealth -= userdmg;

    document.getElementById('attackerBar').setAttribute("style","width:"+attackerHealth+"%");
    document.getElementById('userBar').setAttribute("style","width:"+userHealth+"%");

    $.ajax("/arena/fight-user/"+userId+"/attack/"+attackdmg+"/"+userdmg,
    {

    }); 

    if(userHealth < 0){userHealth = minimum;}
    if(attackerHealth < 0){attackerHealth = minimum;}

    userHp.innerHTML = '<strong>'+userHealth+'</strong>';
    attackerHp.innerHTML = '<strong>'+attackerHealth+'</strong>';

    info.innerHTML = '<strong>' +user.textContent+'</strong>' +' hit <strong>You</strong> with ' +userdmg+' dmg <br> ' + '<strong>You</strong> hit ' 
    +'<strong>'+user.textContent+'</strong>'+ ' with '+ attackdmg +' dmg';
}

});

Answer №1

There seems to be a slight flaw in the logic here. The reason you have to click one more time is because you are defining what should happen at 0 HP before the HP actually reaches zero.

The resolution

Try implementing the following code snippet:

userHealth -= attackdmg;
attackerHealth -= userdmg;
if(userHealth < 0){userHealth = minimum;}
if(attackerHealth < 0){attackerHealth = minimum;}

Prioritize this piece of code

if(userHealth == 0){
...

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

JavaScript and Angular are used to define class level variables

Hello, I'm currently diving into Angular and have encountered an issue with a class level variable called moratoriumID in my component. I have a method that makes a POST request and assigns the returned number to moratoriumID. Everything seems to work ...

Efficiently handling multiple JSON objects in a single PHP function

Currently, I am working on a project that involves populating two dropdown menus where the value of one depends on the other. Specifically, I have three dropdowns - one to select a class, and the other two for selecting subjects and exams based on the sele ...

The Ajax request fails to pass the value to the controller

I've spent the entire day debugging this method and I'm in need of some assistance. My goal is to make an API request and for each array it returns, I want to send a post request to my controller method. However, despite console.log showing the c ...

Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected: export default function Check() { const label = { inputProps: { "aria-label": "termsOfService" } }; const formSchema = yup.object().shape({ ...

Add delayed event listeners to embedded AJAX request beyond function boundaries

I'm working on developing a custom AJAX method extension named getApi that automatically includes my authentication bearer token in the request header. In my code, there is a function called getToken() which retrieves the token either from sessionSto ...

Difficulty encountered in altering button color when the password and confirm password fields are the same in a Vue.js project?

password: '', confirmPassword: '', computed: { empty() { return this.user.password === '' || this.user.confirmPassword === ''; }, equal() { return this.user.password === this.user.confirmPass ...

Calendars malfunctioning following the execution of npm run build

While utilizing the vue2-datepicker for a calendar, I encountered an issue during development. When clicking on the input box in my form, the calendar appeared as expected above the input. However, after running npm run build and loading up the resulting p ...

The validation feature in ASP.NET MVC does not seem to be functioning properly while using

I'm struggling to make the bootstrap modal and asp.net mvc validation work together seamlessly. My form is quite complex with validation displayed in a bootstrap modal. However, when I press the submit button, the validation doesn't seem to be fu ...

What are the steps to implement a queue structure using AJAX?

https://i.stack.imgur.com/RAfAt.png I'm wondering how to upload files consecutively after selecting the overwrite upload or rename upload buttons. Currently, when I press these buttons, I am able to go back and select multiple files for upload at onc ...

Retrieve the string saved in a ViewBag when the ajax call is successful

I am new to ASP.NET MVC and have been struggling to find a solution to this problem. Despite searching on various platforms, including Stack Overflow, I have not been able to resolve it. Here are some links to solutions that did not work for me: Possible ...

Repositioning SVG rectangles made with d3.js (Using d3 or jQuery for this task)

Situation: I'm currently working on integrating a Google map with a d3 overlay, inspired by Mike Bostock's example found here: http://bl.ocks.org/mbostock/899711 This project is being developed within a Rails 4 application, utilizing d3.js and ...

Safari seems to have trouble with jQuery's .ajax() method if it takes a while for the data to be returned

Using the jQuery ajax() method to send data (GET) to an ExportData page and retrieve the result ("succeeded/failed") after the processing is complete. The ExportData page has a delay of around 10 seconds before returning the result. The code functions pro ...

Using regular expressions in JavaScript, eliminate all characters preceding a specified final character

I am attempting to eliminate all text that precedes the last character in a Regex pattern. For example: rom.com/run/login.php Would turn into: login.php Can someone guide me on how to achieve this using JavaScript? I have limited experience with regul ...

The pesky bug in my jQuery checkbox feature

Having trouble resolving a bug where unchecking the square, then red, and rechecking red brings back the red square. Need help preventing any unchecked shapes from being added back when the user toggles colors. My actual project involves many more checkbo ...

Using Node.js to download files with like wget, unzip them, and convert them to JavaScript without saving to

Currently, I am working on a script for a nodejs/express server-side application using the libraries request, unzip, and xml2js. The goal of this script is to fetch a zip file from a specified URL, extract an XML file from it, and then parse that XML into ...

Accessing information from the database when logging in

I am currently working on a mobile application using Slim and Ajax. Within my database, there is a column that stores session codes for logins. After a user logs in, I need to compare the entered username with the database and retrieve the sessionCode asso ...

Guide to creating a continuous loop for CSS3 animation

I'm looking to create a setup that can play on repeat, but I'm not very familiar with jQuery. Can anyone lend a hand with this? Check out the DEMO here $('.title1').fadeIn('fast', function() { $('div').addClass ...

Converting an rrule date value from an array to a customized string format

Here is an array that I am working with: [{ evening_feeding: false evening_feeding_time: "19:00" feeding_frequency_rule: **"FREQ=DAILY;INTERVAL=2"** id: 890 morning_feeding: true morning_feeding_time: "04:00 ...

Using Javascript to automatically replace content when the page is loaded

Having trouble with my fullCalendar jquery calendar and the 'eventClick' method. When I click on an event, the URL is getting encoded incorrectly. For example, I'm trying to pass a Wordpress URL like this: http://sitedomain.com/?post_type= ...

When an element is dragged within the mcustomscrollbar container, the scroll does not automatically move downward

I am facing an issue where I have multiple draggable elements inside a Scrollbar using the mcustomscrollbar plugin. When I try to drag one of these elements to a droppable area located below the visible area of the scroller, the scroll does not automatical ...