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
});
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With