1

I have a simple bootstrap html layout setup, which contains 2 buttons #add and #take. When calling their functions before from the $(document).ready function, everything works, but since I will need to reuse the functions anyway I decided to put them outside.

Now when I click the button nothing happens. Can somebody please tell me what I'm doing wrong?

codepen

html:

<div clas="container">
  <div class="row">
    <div class="col-xs-12">
      <span>Session length:</span>
      <span class="session">25 min</span>
      <button id="add" class="btn btn-info">+</button>
      <button id="take" class="btn btn-info">-</button>
    </div>
    <div class="col-xs-12">
      <h1 id="timer">25:00</h1>
    </div>
    <div class="col-xs-12">
      <button id="start" class="btn btn-success">Start</button>
      <button id="reset" class="btn btn-danger">Reset</button>
    </div>
  </div>
</div>

js:

function addMinute() {
  time + 60;
}

function removeMinute() {
  time - 60;
}

function updateSession(a) {
  $(".session").empty();
  $(".session").append(a + " min");
}

$(document).ready(function() { 
  var time = 1500;

  $("#add").click(function(time) {
    addMinute();
    updateSession(time);
  }) //end add.click
}); //end document.ready
Miha Šušteršič
  • 9,742
  • 25
  • 92
  • 163

1 Answers1

0

Your problem has to do with JavaScript scoping. Your var time is only visible inside that function, and not to the outer functions. You can fix this by making time a global variable or by passing it to the functions you want to use it in.

You can read more about JavaScript's lexical scoping here.

You also have other errors: time + 60 should be time += 60 and time - 60 should be time -= 60.

Saad
  • 49,729
  • 21
  • 73
  • 112
  • updated codepen, still won't work =) – Miha Šušteršič Dec 14 '15 at 13:03
  • You have other errors: Change `time + 60` to `time += 60` and `time - 60` to `time -= 60`. – Saad Dec 14 '15 at 13:04
  • @saadq Time in the event handler is not what the OP thinks it is either. Time passed in will be the event object. – ste2425 Dec 14 '15 at 13:08
  • @ste2425 If you check is updated CodePen, he isn't passing in time anymore, he's using the correct `time` variable. Changing `time + 60` to `time += 60` seems to make it work for me. – Saad Dec 14 '15 at 13:11
  • 1
    @saadq aah my bad, didn't see the updated codepen, just his pasted code in the question. – ste2425 Dec 14 '15 at 13:12