Andrew Nguyen
Andrew Nguyen

Reputation: 1436

If-else statement causing problems with buttons

Update #1 - Clarified question, new working link.


Live link: https://s3.amazonaws.com/bsunproduction/auction/index.html

The problem I'm trying to fix lies with if-else statement for my form buttons on the right column of the page. Scroll down past the header and navigation to see the problem in action. The issue occurs when I do the following:

The end goal

scripts.js

/*-------------------------------------
    STEP ONE: PLACE BID
    --------------------------------------*/

$.ajax({
  url: "https://sheetsu.com/apis/4a8eceba",
  method: "GET",
  dataType: "json"
}).then(function(spreadsheet) {

  // Print current bid
  var currentBid = parseInt(spreadsheet.result.pop().Bids);
  $(".current__amount").html("$" + currentBid);

  var baseAmount = 0;
  var totalAmount = baseAmount;

  $('.button__form').on('click', function() {
    var value = $(this).val();

    if ($(this).hasClass('is-selected')) {
      $(this).removeClass('is-selected');
      $(".check--one").css("color", "#ccc");
      $(".new__amount").css("margin-left", 10 + "px");
      $(".bids__dollar").addClass("is--hidden");
      totalAmount = parseInt(totalAmount) - parseInt(value);
      console.log("If");
      $('.total__amount').html("---");
    } else {
      $(".button__form").removeClass('is-selected');
      $(this).addClass('is-selected');
      $(".check--one").css("color", "#ffdc00");
      totalAmount = currentBid; // reset the totalAmount to base
      totalAmount = parseInt(totalAmount) + parseInt(value);
      console.log("Else");
      $('.total__amount').html("$" + totalAmount);
      $(".bids__dollar").removeClass("is--hidden");
      $(".new__amount").css("margin-left", 0 + "px");

      /*-------------------------------------
      COUNTUP
      --------------------------------------*/

      $(function() {
        var options = {  
          useEasing: true,
            useGrouping: true,
            separator: '',
            decimal: '',
            prefix: '',
            suffix: ''
        };

        var count = new CountUp("count", 0, totalAmount, 0, 1.5, options);
        count.start();
      });
    }
  });
});

index.html (Just the buttons)

<div class="bids__step bids--one">
  <h2>Step One</h2>
  <div class="bids__checkmark">
    <i class="fa fa-check check--one"></i>
  </div>

  <p class="bids__note">Pick one of the amounts below to add to the current bid.</p>
  <div class="buttons">
    <button class="button__form button__one" value="10">$10</button>
    <button class="button__form button__two" value="25">$25</button>
    <button class="button__form button__three" value="50">$50</button>
    <button class="button__form button__four" value="100">$100</button>
    <button class="button__form button__five" value="250">$250</button>
    <button class="button__form button__six" value="500">$500</button>
  </div>
  <!-- /.buttons -->

  <div class="bids__amounts">
    <div class="bids__amount bids__current">
      <p class="bids__note">The last bid was</p>
      <h4 class="current__amount">---</h4>
    </div>

    <div class="bids__amount bids__new">
      <p class="bids__note">Your bid will be</p>
      <h4 class="bids__dollar is--hidden">$</h4>
      <h4 class="new__amount total__amount" id="count">---</h4>
    </div>
    <!-- /.bids__amount -->
  </div>
  <!-- /.bids__amounts -->
</div>

Upvotes: 2

Views: 206

Answers (2)

Josh Crozier
Josh Crozier

Reputation: 240948

The problem is unrelated to the if/else conditions.

The issue is that the count up plugin is overwriting the text (since it is still being executed after you set the text in the if/else conditions).

According to the CountUp.js documentation, the .start() method accepts a function as a callback, which will be executed when the animation ends.

Therefore, the simplest work-around would be to check if there are any selected button elements in the callback. If there aren't any selected elements, then set the text of .total__amount to ---:

var count = new CountUp("count", 0, totalAmount, 0, 1.5, options);
count.start(function() {
  if ($('.button__form.is-selected').length === 0) {
    $('.total__amount').text("---");
  }
});

Alternatively, you could also create an array of count objects.

In the snippet below, there is a counterArray array which contains each count object.

Inside of your if statement, use the .reset() method on each of the count objects in the array before setting the text of .total__amount to ---:

counterArray.forEach(function (count) {
  if (count && count.reset) {
    count.reset();
  }
});

$('.total__amount').text("---");

Here is the relevant code and a working example here.

(Irrelevant code removed for brevity)

var baseAmount = 0;
var totalAmount = baseAmount;
var counterArray = [];

$('.button__form').on('click', function() {
  if ($(this).hasClass('is-selected')) {
    // ....

    counterArray.forEach(function (count) {
      if (count && count.reset) {
        count.reset();
      }
    });

    $('.total__amount').text("---");
  } else {
    // ....

    $(function() {
      var options = {};
      var count = new CountUp("count", 0, totalAmount, 0, 1.5, options);
      count.start();
      counterArray.push(count);
    });
  }
});

Upvotes: 2

Gabriel machts
Gabriel machts

Reputation: 187

The problem is simple: the countup method keeps running and updating the value even after you reset it to "---".

Fortunately, the solution is very simple as well. Add the following line before $('.total__amount').html("---"); :

if (count.typeof == "object") {   // just checking if the count object actually exists.
 count.pauseResume();
 count.reset();
}

In order for this to work you have to make the count object globally available. So change this line:

  var count = new CountUp("count", 0, totalAmount, 0, 1.5, options);

to this: (just remove "var")

  count = new CountUp("count", 0, totalAmount, 0, 1.5, options);

Compare here: http://www.w3schools.com/js/js_scope.asp

Then you should be good!

Note: The methods of the count object I derived from the countup.js file.

Upvotes: 0

Related Questions