heybit
heybit

Reputation: 215

How can I update attributes with jQuery?

$(document).ready(function() {

    var hero_image = new Array();
    hero_image[0] = new Image();
    hero_image[0].src = 'assets/images/link.png';
    hero_image[0].id = 'image';

    hero_image[1] = new Image();
    hero_image[1].src = 'assets/images/bongo.png';
    hero_image[1].id = 'image';

    hero_image[2] = new Image();
    hero_image[2].src = 'assets/images/gandondorf.jpg';
    hero_image[2].id = 'image';

    hero_image[3] = new Image();
    hero_image[3].src = 'assets/images/queen.png';
    hero_image[3].id = 'image';

  var young_hero = ["Link", "Bongo Bongo", "Gandondorf", "Queen Gohma"];
  var health = [100, 70, 120, 50];
  var attack_power = [];
  var counter_power = [];

console.log(hero_image[0]);

function it_is_over_9000(){

  for (var i = 0; i < young_hero.length; i++) {

    var x = Math.floor(Math.random(attack_power)*20) + 3;
    var y = Math.floor(Math.random(attack_power)*10) + 3;

    attack_power.push(x);
    counter_power.push(y);

  }

}

function ready_board(){

  it_is_over_9000();

  for (var i = 0; i < young_hero.length; i++) {
    var hero_btns = $("<button>");
    hero_btns.addClass("hero hero_button");
    hero_btns.attr({
      "data-name": young_hero[i],
      "data-health": health[i],
      "data-image": hero_image[i],
      "data-attack": attack_power[i],
      "data-counter": counter_power[i],
      "data-index": i
    });


    hero_btns.text(young_hero[i]);
    hero_btns.append(hero_image[i]);
    hero_btns.append(health[i]);

    $("#buttons").append(hero_btns);

  }

}

function char(){

 $(".hero_button").on("click", function() {
    var hero = $(this);
    var hero_select = hero.data('index');


    for (var i = 0; i < young_hero.length; i++) {

      //var attack = ;

      if (i != hero_select){

        var enemies = $("<button>");
        enemies.addClass("hero enemy");

        enemies.attr({
          "data-power" : it_is_over_9000(),
          "data-name": young_hero[i],
          "data-health": health[i],
          "data-image": hero_image[i],
          "data-attack": attack_power[i],
          "data-counter": counter_power[i],
          "data-index": i
        });

        enemies.text(young_hero[i]);
        enemies.append(hero_image[i]);
        enemies.append(health[i]);

        $("#battle").append(enemies);

      }

    }

    $("#buttons").html($(this).data('name','health','image'));

    defender();

  });
}

function defender(){

  $(".enemy").on("click", function() {

    var enemy = $(this);
    var enemy_select = enemy.data("index");
    console.log(enemy_select);
    for (var i = 0; i < young_hero.length; i++) {

      if (i == enemy_select) {

        var defender = $("<button>");
        defender.addClass("hero defender");

        defender.attr({
          "data-name": young_hero[i],
          "data-health": health[i],
          "data-image": hero_image[i],
          "data-attack": attack_power[i],
          "data-counter": counter_power[i],
          "data-index": i
        });

        defender.text(young_hero[i]);
        defender.append(hero_image[i]);
        defender.append(health[i]);

        $("#defend").append(defender);

        $(this).remove();

      }

    }
  });

}

  $(".defend_button").on("click" , function(){

      if($(".defender").data("health") == 0){

        $(".defender").remove();

      } 

        $(".defender").attr({
          "data-health":  $(".defender").data("health") - $(".hero_button").data("attack")
        });       
  });

ready_board();
char();

});

I am trying to make a RPG game and I have the characters being generated the way I want them too but on the $(".defend_button").on("click" , function() at the end it doesn't update the data-health as it should. It only updates once but upon many clicks on the defend-button it doesn't update past the first time.

    <!DOCTYPE html>
<!DOCTYPE html>
<html>
<head>

      <meta charset="UTF-8">
    <title>Zelda</title>

    <script type='text/javascript' src='https://code.jquery.com/jquery-2.2.0.min.js'></script>

    <script type = "text/javascript" src = "assets/javascript/game.js"></script>

    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <link rel="stylesheet" type="text/css" href="assets/css/style.css">

</head>

<style type="text/css">
    .hero { width: 125px; height:150px; border-style: solid; padding: 2px; float: left; margin: 2px; float: left; }

  .letter-button-color { color: darkcyan; }

  .fridge-color { color: orange; }

  #display { margin-top:78px; height:500px; width:220px; margin-left:60px; }

  #buttons { padding-top:60px; }

  #clear { margin-left: 20px; font-size: 25px; color: black; border-style: solid; width: 100px; }

    #image{width: 100px; height: 100px; margin-left: 10px;  }

</style>

<body>

<div class="row">

<div class="col-md-8">Select Your Character</div>

</div>

<div class="row">

<div id="buttons" class="col-md-8"></div>



</div>

<div class="row">

<div id="battle" class="col-md-8">


</div>

</div>

<div class="row">
    <div class="col-md-8">
        <button class="btn btn-primary defend_button">Defend</button>
    </div>
</div>

<div class="row">

<div id="defend">


</div>

</div>





</body>
</html>

Upvotes: 3

Views: 372

Answers (2)

Louys Patrice Bessette
Louys Patrice Bessette

Reputation: 33933

You have to use .data() to update the health value.

var battleResult = $(".defender").data("health") - $(".hero_button").data("attack");
console.log("battleResult should be: "+battleResult );

$(".defender").data({
    "health":  battleResult
});

I played a little with your game.
I found how to update the health display below the image too...
Since only updating the data wasn't changing anything on the screen.

So, I left the above code there, for you to see it is effectively working.
But since you have to re-create the button to update health on scrreen... It is kind of useless.

I also fixed the death condition
from if($(".defender").data("health") == 0){
to     if($(".defender").data("health") <= 0){

I have to stop here before changing to much things.
See it in CodePen

Check your loop in it_is_over_9000(), because I think it is running uselessly too often.
And a dead defender has to be "buried" (lol).
Because when it is killed, a click on the defend button is kind of ressurrecting it. ;)

Upvotes: 1

ermish
ermish

Reputation: 1270

Try setting the attribute like this. Also, I recommend putting $(".defender") in a variable so you aren't requerying it each time.

var defender = $(".defender");

var loweredHealth = defender.data("health") -  $(".hero_button").data("attack");
defender.attr('data-health`, loweredHealth);

Update:

It looks like the $('.defender') call will return multiple items. You either need to select a specific defender or iterate through them individually like so:

$('.defender').each(function(i, nextDefender) {
    var loweredHealth = nextDefender.data("health") -  $(".hero_button").data("attack");
    nextDefender.attr('data-health`, loweredHealth);
});`

Upvotes: 0

Related Questions