JJJollyjim
JJJollyjim

Reputation: 6207

Using JQuery replaceWith with a JavaScript Variable

Here's my html:

<div class="timer">Not Started</div>

And JS/JQ:

var seconds = 10;
  var minutes = 0;

  setTimeout("updateTimer()", 1000);

  function updateTimer() {

     if (seconds == 0 && minutes != 0) {
        minutes -= minutes;
        seconds = 59;
        alert (seconds);
     } else if (seconds == 1 && minutes == 0) {
        alert ('done');
     } else {
        seconds = seconds - 1;
        //alert (seconds);
        $(".timer").replaceWith(seconds);

     }

     setTimeout("updateTimer()", 1000);

  }

Instead of replacing Not Started with 10, 9, 8..., Not Started disappears.

Upvotes: 0

Views: 1918

Answers (2)

Anurag
Anurag

Reputation: 141869

$(".timer").text(seconds);

You can't replace a DOM node with a string.

See an example.

You could simplify your logic further by making use of setInterval instead of setTimeout, and use total seconds for easier calculations and remove minutes.

var seconds = 10, minutes = 0;
var totalSeconds = (minutes * 60) + seconds;

var timerId = setInterval(updateTimer, 1000);

function updateTimer() {
    $('.timer').text(totalSeconds % 60);

    if (totalSeconds == 0) {
        alert("done");
        clearInterval(timerId);
    }

    totalSeconds--;
}

Upvotes: 2

Rob Williams
Rob Williams

Reputation: 1470

replaceWith will replace the entire div, not just the contents. Try this instead:

$(".timer").html(seconds);

Upvotes: 0

Related Questions