As part of a beginner challenge on freecodecamp.com, I was tasked to create a random quote generator. The main requirement was that a user had to be able to tweet their quote.
I wanted to give the user some options to customize their quote so I added three input fields for a subject, verb and noun (in my code I refer to the noun input as object). In my script I created an empty array variable for each input field. Each input field has a button, that when pressed will save the input to the each empty array respectively.
After a user enters a value in each input field and selects the enter buttons, other events will trigger that will remove and add classes to the input fields and buttons. The event deactivates the label, input box and button, essentially hiding them. The event also adds an activate class to a <span> tag to display a confirmation word. The activate class is a fairly simple trick that adds a class with a display: block; property to the element that had previously been display: none;
Here is the result of when a user has selected the Enter button for Subject:
Underneath the three input areas I added a <p> tag, larger button to generate the quote, a reset quote link to reset the values and a link to tweet the quote.
For the possible random quote results I created six variables with random strings which include the subject, verb and noun values. I then created an array to contain all six variables.
Next, I had to create two functions that would pick one of the random string outputs when the user clicked on the generate quote button. The rand function returns a whole number between 1 and 6. Inside the randomQuote function I created an output variable equal to a random index value in the variable arr, then returned it. Finally, I created another variable myQuote equal to the return value of the radomQuote function. I did this because it was easier to reference the variable myQuote rather than the function randomQuote.
When the generate quote button is clicked the text area changes to the value of myQuote, which is one of the random strings.
For the twitter button I had some help from Evan Mullins, who is an experienced Twitter celebrity. He explained that I could add an <a> tag with an href equal to a special url that opens a tweet option page. In my script file I set the <a> class attr equal to the url plus the quote output.
Finally, I created a click event for the reset quote link. The event resets the text area back to its original state, removes the values from the subject, verb and noun arrays, returns the input fields back to and removes the confirmation words.