Random Quote Machine - Revealing the Author

Random Quote Machine - Revealing the Author
0.0 0

#1

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… Can someone explain why this is happening/offer a solution?

The relevant code is the Javascript, I know the CSS looks wonky at the moment.

Thank you!


#2

The problem is the following section of code:

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

Every time a new quote is retrieved via the getJSON function, you are adding an additional “click” event handler for the button with id=“authorButton”. The first time the refresh button is clicked everything works fine, because there is only one click event handler for the button with div=“authorButton”. The second time the refresh button is clicked, there are now two click events for the button with div=“authorButton”, so the first click handler runs the $(this).text(function(i, text) { which causes the text of the button to switch to an author’s name, but immediately after that, the same code executes again which switches it to “Click to Reveal”. All of this happens very quickly, so you only see “Click to Reveal”. Every other time, you will actually see an author.

How to solve this dilemma? One way is to take the following steps:

  1. Move the click event handler for the button with div=“authorButton” to be outside the callback function of the click handler for the refresh button
  2. Declare jsonAuthor as a global variable outside the same callback function
  3. Remove the declaration of jsonAuthor inside the getJSON callback function and simply assign the value of json.quoteText to the globally declared jsonAuthor.

There are other solutions, but this one will minimize the changes to your existing code. The one “side-effect” of my solution above is that if you click on the “Click to Reveal” before clicking the refresh button the first time, you will see undefined instead of “Click to Reveal” as the text of the author button. One way to deal with that is to hide this button until the refresh button is clicked which can be done using the css property of visible:hidden; and then using the show function in JQuery.


#3

Oh my goodness, I tried everything you mentioned earlier, but I was still declaring jsonAuthor as a variable in the getJSON instead of assigning it.

This makes so much more sense, thank you!!