Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my .on("click") function for the AuthorButton only returning my variable every other quote?

Tags:

Some background: I am working through FreeCodeCamps Front-End Development projects and this project represents a Random Quote Machine.

I would like to keep the author hidden for each quote, but at the moment, the "Click to Reveal" button only reveals an author every other quote...

https://codepen.io/DecisiveIndecisive/pen/KXjXXd

The code in question is the Javascript. Thank You!

$(document).ready(function() {
  var url =
    "https://api.forismatic.com/api/1.0/?method=getQuote&key=1&lang=en&format=jsonp&jsonp=?";

  $("#refreshButton").on("click", function() {
    $.getJSON(url, function(json) {
      var jsonQuote = json.quoteText;
      var jsonAuthor = json.quoteAuthor;
      $(".counter").html(jsonAuthor);
      $("#authorButton").text("Click to Reveal");

      if (jsonAuthor === "") {
        $("#refreshButton").trigger("click");
      } else {
        $(".message").html(jsonQuote);
        $("#authorButton").click(function() {
          $(this).text(function(i, text) {
            return text === "Click to Reveal"
             ? "- " + jsonAuthor
              : "Click to Reveal";
          });
        });
      } //else close
    }); //getJSON close
  }); //refreshButton Close
});
like image 578
Xerxes Clayton Avatar asked Nov 14 '17 16:11

Xerxes Clayton


1 Answers

The problem here is that you're re-binding the click function every time the refresh button is clicked. This means that when it is clicked for the second quote, the same effective function is invoked twice. You can see this in action if you add a log message inside of your #authorButton click handler.

$("#authorButton").click(function() {
  $(this).text(function(i, text) {
     console.log(text)
     return text === "Click to Reveal" ? "- " + jsonAuthor : "Click to Reveal";
  });
});

A better option would be to have a hidden element which you can update with the jsonAuthor when you get your json feed. Then have a single #authorButton click handler which shows that hidden element when invoked.

like image 197
Daniel Westendorf Avatar answered Sep 19 '22 12:09

Daniel Westendorf