Search code examples
javascriptjqueryhtmlupdating

Updating Variable in HTML with JQuery


I'm a beginner programmer and I'm building a game. Whenever the player clicks on the gold image, he should get 1 gold. So I have the following HTML piece of code:

<li id="gold">Gold: 0</li>

That's the starting gold, and through JQuery I update that with:

$('#gold-image').click(function() {
    gold++;
    $('#gold').replaceWith('<li id="gold">Gold: ' + gold + '</li>');
});

But I don't feel that's the best way to update how much gold the player has. Is there a way that I can write in the HTML to update the variable whenever it's being changed or something like that without having to replace that whole item?

Later in the game there will be many functions running at the same time and increasing the gold number, so I think replacing HTML code is not the optimal way.


Solution

  • Try this with your existing div <div id="gold">Gold: 0</div>:

    $('#gold-image').click(function() {
        gold++;
        $('#gold').html('Gold: ' + gold);
    });
    

    Although the above code would work. I would NOT use jQuery for something like this. There are other frameworks which would be way better for such applications. For example you can take a look at AngularJS or Ember.

    The same functionality can be achieved using the two-way binding with AngularJS.

    1) the markup:

    <div controller="GameCtrl">
      <img src="/path/to/img.png" ng-click="goldClicked()">
      <div>Gold {{ gold }}</div>  
    </div>
    

    2) the javascript code

    app.controller('GameCtrl', function($scope) {
      $scope.gold = 0;
      $scope.goldClicked = function() {
        $scope.gold += 1;
      };
    });
    

    The code is very very simple and you do not need to deal with selectors. Every time you change the gold (or any other variable) it will automatically be updated in the DOM. You will automatically get modular code and dependency injection. In addition you will write everything declaratively and your code will be much easier to read and easy to change in future.

    UPDATE: Here is a working AngularJS fiddle: http://jsfiddle.net/absolutemystery/7WgYK/