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

Some background: I'm working on Front-End Development FreeCodeCamps projects, and this project is a random quote station.

I would like to leave the author hidden for each quote, but at the moment the "Click to Reveal" button only opens the author of every other quote ...

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

This code is Javascript. Thanks!

$(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 }); 
+5
source share
2 answers

The problem is that you re-bind the click function every time you click the refresh button. This means that when you click on the second quote, the same effective function is called twice. You can see this in action if you add a log message inside your #authorButton click #authorButton .

 $("#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 that you can update with jsonAuthor when you get your json feed. Then use one click #authorButton handler, which shows that the hidden element is invoked.

+2
source

Each time you download a new quote, you add a new click listener. Then, when you check text === "Click to Reveal" , the listener is called x times, and the text is updated every time.

+2
source

Source: https://habr.com/ru/post/1273363/


All Articles