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

I am having trouble retrieving a JsonResult from an asp.net mvc controller using $resource in angular

I am new to Angularjs and trying to integrate it with asp.net mvc. I am facing an issue where I am unable to access an asp.net mvc controller to return a JsonResult using $resource in angular. Strangely, when I use $.getJson in JavaScript directly, it work ...

How to move a div beneath the JavaScript files in Drupal 7

I am facing a challenge where I need to position a div right above the body tag without interfering with the scripts located above it. Despite my efforts, I have not been successful in achieving this goal. I attempted to use Hook_page_build to position t ...

Modifying iframe src using click event from a separate component in Angular 10

I am looking to dynamically update the src attribute of an iframe when the menu bar is clicked. The menu bar resides in a separate component and includes a dropdown menu for changing languages. Depending on which language is selected, I want to update the ...

Implementing a sibling combinator technique within Material UI's useStyles framework

Is there a way to change the background of one div when hovering over another using material ui? The traditional CSS method is: #a:hover ~ #b { background: #ccc; } Here is my attempt with Material UI: const useStyles = makeStyles(theme => ({ ...

Is there a standard event triggered upon the closing of a browser tab or window?

Does React have a built-in event that is triggered when a browser tab or window is closed? If it does, does it have support across different browsers? ...

Is there a way to toggle the slide effect of one 'div' without affecting another one?

Hey everyone! I am new to jquery and currently working on a project with two div elements that are slidetoggled. The issue I am facing is that when I open or close one div, the other div also moves along with it. I understand what is happening in the back ...

Google Scripts: Generating a set of data to include in an email

As a newcomer to Google Script and JavaScript, I'm on a mission to email a list of file names extracted from a spreadsheet. The names reside in a column within my sheet, and after defining a variable called "newfiles" to cherry-pick only the necessary ...

Troubleshooting the Issue with Jquery Menu and Mouse Pointer

Recently, I've been attempting to modify the cursor behavior on a navigation menu that I stumbled upon at HTML Drive's JQuery Menu. I experimented with CSS and jQuery. In my JQuery attempt, I utilized... $("body").hover(function() { $(this).cs ...

Execute jQuery's .one() function only when in the viewport

As I work on creating a progress bar that plays when in viewport, I've encountered a hiccup. The code executes every time and ends up generating multiple progress bars instead of running just once. The following code snippet is part of a Joomla Extens ...

Verify if an array contains a specific string while disregarding any additional letters within that string

Let's say I have a variable: var url = "/login/user"; Along with an array: var x = ["login", "resetpassword", "authenticate"]; My goal is to check if the url string exists within the array. The issue arises because the url contains additional char ...

Unable to transfer a value from a CGI script back to an HTML form

When working with an HTML form that has a date field named cdt, I encountered the need to retain the date value when submitting data to an Oracle table through a CGI script. To achieve this, instead of using Javascript code like history.go(-1), I aimed to ...

Select an option from the dropdown menu to populate the contents of the second dropdown list

The provided code dynamically populates the initial dropdown list with unique pants brands: $.each(pantsBrands, function(i){ var li = $('<li>') .appendTo(pantsList); var aaa = $('<a>') .text(pantsBra ...

Tips for modifying the properties of variables within an array using JavaScript

I have an array that holds variables used to control a specific template. divisionsListToManipulate: ['showActivitiesSection', 'hideAssignActionplanDiv', 'displayProp ...

Navigating nested events with jQuery

Currently, I am dealing with a <span class="fold"></span> element that is controlled by the following jQuery code: $('.fold').click(function (event) { ... }); As new "fold" elements are added dynamically via ajax, I need to assign ...

Step-by-step guide on implementing a fade effect to a specific JavaScript element ID

When I click a button, the image on the screen disappears. I am looking to add a fade effect to this action. Can someone help me achieve this using CSS? #hide{-webkit-transition: all 1s ease-in-out;} For reference, here is a demo showcasing the current b ...

To restore the position of the chosen object in Three.js after clicking reset

I am facing an issue with resetting the position of my latest Object in three.js. Initially, my code consists of the following: function onDocumentMouseDown( event ) { event.preventDefault(); var vector = new THREE.Vector3( mouse ...

What is the best way to eliminate the Iframe scrollbar while ensuring that the entire page loads?

When I add an Iframe inside the contentArea, two scroll bars appear. I am looking for a way to hide the iframe scrollbar without hiding any of the external website's content. I have tried using the scrollbar="no" snippet code, but it didn&ap ...

Reorganize containers without relying on bootstrap styling

Is there a method to rearrange the order of two divs without using the bootstrap library? <div class='parent'> <div class='child-1'>Abc..</div> <div class='child-2'>Xyz..</div> </div> I ...

Issue with retrieving query results using node_redis client

I've been struggling with a particular issue that I just can't seem to solve. The problem revolves around not being able to retrieve output values from a Redis query. My setup involves using the node_redis client as the Redis driver for my Node.J ...

Select2.js Dropdown List with Case Sensitivity

Currently making use of select2.js version 4.0.3 Situation: Imagine the dropdown list contains the following options: JavaScript javascript Javascript javaScript So, when a user types in java, all options are displayed (case is n ...