Sam Henrichs Sam Henrichs - 4 months ago 7
jQuery Question

Creating variables, using them in functions, and calling functions

I'm creating variables in jQuery, then creating a function to display them in html, and then calling the function. It's not working. Bear in mind I"m new to using javascript this way, and usually only use it for animation. Here is my code:

HTML:

<div class="year" id="growth"></div>
<div class="year" id="metro"></div>
<div class="year" id="pioneer"></div>
<div class="year" id="shady"></div>
<div class="year" id="stryker"></div>
<div class="year" id="tri"></div>
<div class="year" id="auto"></div>
<div class="year" id="uranium"></div>
<div class="year" id="valley"></div>


jQuery:

$(document).ready(function() {

var growth = 100;
var metro = 100;
var pioneer = 100;
var shady = 100;
var stryker = 100;
var tri = 100;
var auto = 100;
var uranium = 100;
var valley = 100;

function growth() {
$('#growth').html(growth);
};
function metro() {
$('#metro').html(metro);
};
function pioneer() {
$('#pioneer').html(pioneer);
};
function shady() {
$('#shady').html(shady);
};
function stryker() {
$('#stryker').html(stryker);
};
function tri() {
$('#tri').html(tri);
};
function auto() {
$('#auto').html(auto);
};
function uranium() {
$('#uranium').html(uranium);
};
function valley() {
$('#valley').html(valley);
};


growth();
metro();
pioneer();
shady();
stryker();
tri();
auto();
uranium();
valley();

});


Help is very much appreciated!

Answer

The problem is, that your override the values/functions because you are using the same names.

var a = 1;
function a() { 
  console.log(a) // function..
}

You should rename your functions or variables of the values, or use an object to wrap your values.

var values = {
  growth:  100,
  metro:   100,
  pioneer: 100,
  shady:   100,
  stryker: 100,
  tri:     100,
  auto:    100,
  uranium: 100,
  valley:  100
}

And use it in your functions

...
function valley() {
   $('#valley').html(values.valley);
}

(DRY) -> Don't repeat yourself

Just as an idea, you could make your code a bit smaller by using loops with a generic function, because your values and ids, have the same names, so instead of writing all the function by hand, you could create a one function, which will do it for all:

$(document).ready(function() {
  var values = {
    growth:  100,
    metro:   100,
    pioneer: 100,
    shady:   100,
    stryker: 100,
    tri:     100,
    auto:    100,
    uranium: 100,
    valley:  100
  }

  // Generic function
  function setValueForId(id) {
    $('#' + id).html(values[id])
  }

  Object.keys(values).forEach(setValueForId)
})