DEV Community

Muna Mohamed
Muna Mohamed

Posted on

A Random Quote Generator with a Night/Day feature tutorial

So you’ve just completed building yet another random quote generator, and you don’t know where to go from here. Or maybe this is your first. Here’s where this tutorial comes in! With a simple feature, your random quote generator no longer is 'yet another random quote generator' — it’s one with a twist.

Let’s get started!

HTML

<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
</head>
<body>
  <button id="night-mode-js" class="btn night-mode" data-text-swap="day-mode" onclick="toggleBtn()">
  Night-mode
  </button>

  <div class="quote-container">
    <h2 id="heading">Motivational Quotes</h2>
    <p id="quote-js" class="quote">Do not wait; the time will never be ‘just right.’ Start where you stand, and work with whatever tools you may have at your command, and better tools will be found as you go along. — George Herbert</p>
    <button id="quote-btn">Get a quote</button>
  </div>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

With the components that make up the Windows Login page in mind, we can now start to write our HTML code.

Our HTML structure is very simple. Following our sketch, we’ll have a button tag centered at the top of the page which will be our night/day toggle button. We’ll give the button an id of night-mode-js and a class of btn and night-mode. Giving our button an id of night-mode-js will aid us in knowing which components of our quote generator we have applied javascript to. We will use the btn class to apply CSS styling and the night-mode class will be the class that we will toggle to apply the night or day mode to our quote generator.

Below that will be our quote generator. We’ll start off with the main div container which we will act as the container for all of the components of the quote generator (minus the night/day mode button above) and we’ll give it a class name of quote-container. Nested inside the quote-container div will be the heading, the quote display and our button that will allow us to generate random quotes. The heading will be in a h2 tag which we will give an id of heading. Under the header will be the quote display. To display our quotes, we will use a

tag which we will give an id of quote-js and class of quote-display. Our final component that will be in the quote-container div will be the our other button, quote-btn, which will allow us to generate the random quotes.

Here’s what we have so far:

SCSS

.btn {
  width: 120px;
  height: 30px;
  display: block;
  margin: 0 auto;
  border-radius: 30px;
  font-family: helvetica;
  text-align: center;
  text-transform: uppercase;
  background-color: white;
  border: 1px solid black;
  cursor: pointer;
}
.quote-container {
  max-width: 700px;
  min-width: 350px;
  margin: 30px auto;
  text-align: center;
  border: 2px solid #37474F;
  border-radius: 10px;     
  transition: all 0.5s ease-in;
  color: #37474F;
  font-family: helvetica;
#heading {
    font-size: 28px;
  }
  .quote-display {
    line-height: 30px;
    margin: 30px;
    padding: 20px;
    border: 1px solid #BDBDBD;        
    font-style: italic;
    font-size: 18px;
  }
  #quote-btn {
    margin: 20px;  
    text-transform: uppercase;
    background-color: white;
    border: 1px solid #9E9E9E;
    padding: 10px 30px;
    cursor: pointer;
    transition: background-color 0.3s ease-in;
    &:hover {
      background-color: #37474F;
      color: white;
    }
  }  
}
.night-mode {
  background-color: #37474F;
  color: white;   
}
Enter fullscreen mode Exit fullscreen mode

Let’s do some styling!

Night/day toggle button

We’ll start by styling our first button (i.e. our night/day mode toggle button). We’ll give it a width of 120 pixels and a height of 30 pixels.

Since most browsers display buttons as inline-block elements (which means that the browser allows other elements to sit on either side of the button), we’ll change this so that it displays as a block.

To center the button horizontally, we’ll give it a margin of 0 auto. To slightly curve the corners of the button, we’ll give the border-radius property a value of 30 pixels.

We’ll change the font-family value to helvetica. To center the text within the button, we’ll give the text-align property a value of center and in order to change the letters so that they are uppercase we’ll give the text-transform property a value of uppercase.

We’ll also give the button a background-color of white as well as a thing black border that is 1 pixel. To indicate to that this is a button that can be clicked, we’ll change the cursor property to give it a value of pointer. After applying all the styling, our button will look like something like this:

Quote-container

The next component to style is the quote-container div.

We’ll give the quote-container div a max-width of 700 pixels and a min-width of 350 pixels. This will allow the container for the quote generator to be responsive by allowing it to shrink to a width of 350 pixels and expand to a maximum width of 700 pixels.

To create some space between the night/day-mode button and the quote-container and also center the quote-container horizontally, we’ll give the margin property of a value of ’30 px auto’.

We’ll center the text within the quote-container by applying a text-align of center. To add a slight curvature to our quote-container, we’ll apply a border-radius of 10 pixels. To apply a small transition effect which will apply when something happens to the quote-container and/or its child elements, we’ll use the transition property. The transition will last for 0.3 seconds and we will set the transition-timing function to ease-in

In order for the text in the quote-container to appear less harsh, we’ll change the color of the text from the default color (which is black) to a more muted grey colour (#37474F to be exact). Finally, for uniformity, we’ll make the font-family for the quote-container to be helvetica. This will not only apply to the quote-container div but also all of its child elements too.

Heading

Because most of the CSS properties that we applied to the quote-container apply to the heading too, the only property we’ll apply to the heading will be a font-size of 28 pixels.

Quote -display

To the p tag that will display the quotes, we’ll apply a line-height of 30 pixels to create some spacing between each line of a quote. We’ll also apply a margin of 30 pixels to create some space between the main container, quote-container, and the p tag that will be displaying our quotes. Furthermore, we’ll add some padding between the text that will be in the p tag (i.e our quote display) and its container (the p tag itself). We’ll add a thin black border that is 1 pixel, make the font italic by giving the font-style property a value of italic and finally, changing the font-size to 18 pixels.

Quote-btn

Let’s start by giving the quote button a margin of 20 pixels. Next, we’ll give the quote button a white background and a thin border that’s 1 pixel and a color of #9E9E9E. We’ll apply a small bit of padding on the top and bottom of the button that’s 10 pixels, and 30 pixels of padding on the left and right of the button. Finally, we’ll use the transition property to apply an ease-in transition that lasts for 0.3 seconds to the background-color which will apply the transition whenever we hover over the button. The last thing to do is apply a hover effect in order to change the background-color and color of the text when the cursor hovers over the button. We do this using the :hover selector.

By the end of the styling, this is what our quote generator will look like:

jQuery

var quote = document.getElementById("quote-js");
var quoteBtn = document.getElementById("quote-btn");

// Nightmode/Daymode feauture
$(document).ready(function() {
  $("#night-mode-js").click(function() {
    $(".quote-container, .quote, .btn").toggleClass("night-mode");
       if($('#night-mode-js').hasClass('night-mode')){
       $('#night-mode-js').html('Night-mode');
     } else {
       $('#night-mode-js').html('Day-mode');
     }
  });
});

//Random quote machine
var quotes = [
  '"The past cannot be changed. The future is yet in your power." - Unknown',
  '"Either I will find a way, or I will make one." - Philip Sydney',
  '"Failure will never overtake me if my determination to succeed is strong enough." - Og Mandino',
  '"Dont watch the clock; do what it does. Keep going." — Sam Levenson',
  '"Aim for the moon. If you miss, you may hit a star." — W. Clement Stone.',
  '"It always seems impossible until its done." - Amelia Earhart',
  '"Look up at the stars and not down at your feet. Try to make sense of what you see, and wonder about what makes the universe exist. Be curious." - Stephen Hawking',
  '"Believe in yourself! Have faith in your abilities! Without a humble but reasonable confidence in your own powers you cannot be successful or happy." - Norman Vincent Peale', '"You Learn More From Failure Than From Success. Dont Let It Stop You. Failure Builds Character." – Unknown', '"If You Are Working On Something That You Really Care About, You Dont Have To Be Pushed. The Vision Pulls You." – Steve Jobs','"We May Encounter Many Defeats But We Must Not Be Defeated." – Maya Angelou', '"One Of The Lessons That I Grew Up With Was To Always Stay True To Yourself And Never Let What Somebody Else Says Distract You From Your Goals." – Michelle Obama', '"Todays Accomplishments Were Yesterdays Impossibilities." – Robert H. Schuller', '"The Only Way To Do Great Work Is To Love What You Do. If You Havent Found It Yet, Keep Looking. Dont Settle." – Steve Jobs', '"Twenty years from now you will be more disappointed by the things that you didnt do than by the ones you did do, so throw off the bowlines, sail away from safe harbor, catch the trade winds in your sails. Explore, Dream, Discover." - Mark Twain', '"Nothing is impossible, the word itself says "Im possible!" - Audrey Hepburn', '"Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time." - Thomas A. Edison', '"I learned that courage was not the absence of fear, but the triumph over it. The brave man is not he who does not feel afraid, but he who conquers that fear." – Nelson Mandela', '"If you dont like something, change it. If you cant change it, change your attitude." – Maya Angelou', '"Success means doing the best we can with what we have. Success is the doing, not the getting; in the trying, not the triumph. Success is a personal standard, reaching for the highest that is in us, becoming all that we can be." – Zig Ziglar'
];
quoteBtn.onclick = function randomQuote() {
  var rand = quotes[Math.floor(Math.random() * quotes.length)];
  quote.innerHTML = rand;
};
Enter fullscreen mode Exit fullscreen mode

The end is near!

So in this tutorial, jQuery will be our JavaScript library of choice. JQuery is a fantastic library that is easy to learn, use and read and is the perfect JavaScript library to start learning as a beginner. You can achieve the same results with other JavaScript libraries and frameworks or even with vanilla JavaScript but for the sake of this tutorial, which i geared towards codenewbies who are starting out with JavaScript, we’ll use jQuery.

Okay, explanations aside, let’s begin by declaring the quote-display using its id, quote-js, and storing it in a variable called quote. We’ll also declare the quote button using it’s id, quote-btn, and storing it in a variable called quoteBtn.

Night/day mode feature

We’ll start with the night/day mode feature. First, we’ll begin with jQuery’s ready function. The ready() let’s the browser know what to run after the page is loaded.

$(document).ready(function(){
   //Enter code here
});
Enter fullscreen mode Exit fullscreen mode

So let’s review what we want to happen. We want the night/day toggle button to toggle it’s background-color, text-color and text within the button between ‘night-mode’ to ‘day-mode’ when it is clicked. We also want the background-color and text-color of the quote-container, quote-display and quote-btn to toggle between day-mode colors and night-mode colors.

The simplest way of doing this is to add a class called night-mode in our stylesheet and give it the features we want the components of our quote-generator to have when the night-mode class is applied. I’ve included this class at the end of my stylesheet, giving it a background-color of #37474F and a text-color of white.

$(document).ready(function() {
 $(“#night-mode-js).click(function() {
    //Enter code here
 });
});
Enter fullscreen mode Exit fullscreen mode

Within our ready() event , we will type in a click() event that will apply to the night/day toggle button. We will use the id we gave it specifically for use in our JavaScript code.

$(document).ready(function() {
  $("#night-mode-js").click(function() {
    $(".quote-container, .quote, .btn").toggleClass("night-mode");
  });
});
Enter fullscreen mode Exit fullscreen mode

Within our click() event is our toggleClass() event. We will type in which components we want the toggleClass() method to apply to as well as what class we want to toggle between, which will apply to the components we specified before.

What toggleClass() does is toggle between adding or removing the class to the components specified. So when we click the night/day toggle button, the function within our click() event will run which will execute the toggleClass() event. If the components listed already have the night-mode class, the toggleClass() event will remove it when the night/day toggle button is clicked. If they don’t have the night-mode class, then the toggleClass() event will add the class to each component specified in the method.

$(document).ready(function() {
  $("#night-mode-js").click(function() {
    $(".quote-container, .quote, .btn").toggleClass("night-mode");
       if($('#night-mode-js').hasClass('night-mode')){
       $('#night-mode-js').html('Night-mode');
     } else {
       $('#night-mode-js').html('Day-mode');
     }    
  });
});
Enter fullscreen mode Exit fullscreen mode

The last thing we need to happen when the night/day toggle button is clicked is for the text within the button to toggle between ‘night-mode’ and ‘day-mode’. We do this using an if statement and the hasClass() event. When clicked, If the night/day toggle button has the night-mode class, we want the text within the button to be ‘night-mode’. If the night/day toggle button doesn’t have the night-mode class (remember we’re using the toggleClass() event to toggle between adding or removing the night-mode class from the elements we listed earlier), then we want the text within the button to be ‘day-mode’.

That’s it for the night/day-mode feature! Let’s move on to the final step in the tutorial — is the quote-generator itself.

Quote-generator

We’ll begin by declaring our quotes array that will store our array of quotes that will be displayed at random in our quote-generator and give it the variable name quotes. In this tutorial, we’ll be using motivational quotes.

You can use whatever category of quotes you would like; book quotes, movie quotes, TV-show quotes. Or if quotes are not your thing, how about a random facts about a topic of your choice? You can even use jokes! You have full control here so go wild!

var quotes = [
  '"The past cannot be changed. The future is yet in your power." - Unknown',
  '"Either I will find a way, or I will make one." - Philip Sydney',
  '"Failure will never overtake me if my determination to succeed is strong enough." - Og Mandino',
  '"Don’t watch the clock; do what it does. Keep going." — Sam Levenson',
  '"Aim for the moon. If you miss, you may hit a star." — W. Clement Stone.',
  '"It always seems impossible until its done." - Amelia Earhart',
  '"Look up at the stars and not down at your feet. Try to make sense of what you see, and wonder about what makes the universe exist. Be curious." - Stephen Hawking',
  '"Believe in yourself! Have faith in your abilities! Without a humble but reasonable confidence in your own powers you cannot be successful or happy." - Norman Vincent Peale', '"You Learn More From Failure Than From Success. Don’t Let It Stop You. Failure Builds Character." – Unknown', '"If You Are Working On Something That You Really Care About, You Don’t Have To Be Pushed. The Vision Pulls You." – Steve Jobs','"We May Encounter Many Defeats But We Must Not Be Defeated." – Maya Angelou', '"One Of The Lessons That I Grew Up With Was To Always Stay True To Yourself And Never Let What Somebody Else Says Distract You From Your Goals." – Michelle Obama', '"Today’s Accomplishments Were Yesterday’s Impossibilities." – Robert H. Schuller', '"The Only Way To Do Great Work Is To Love What You Do. If You Haven’t Found It Yet, Keep Looking. Don’t Settle." – Steve Jobs', '"Twenty years from now you will be more disappointed by the things that you didn’t do than by the ones you did do, so throw off the bowlines, sail away from safe harbor, catch the trade winds in your sails. Explore, Dream, Discover." - Mark Twain', '"Nothing is impossible, the word itself says "I’m possible!" - Audrey Hepburn', '"Our greatest weakness lies in giving up. The most certain way to succeed is always to try just one more time." - Thomas A. Edison', '"I learned that courage was not the absence of fear, but the triumph over it. The brave man is not he who does not feel afraid, but he who conquers that fear." – Nelson Mandela', '"If you don’t like something, change it. If you can’t change it, change your attitude." – Maya Angelou', '"Success means doing the best we can with what we have. Success is the doing, not the getting; in the trying, not the triumph. Success is a personal standard, reaching for the highest that is in us, becoming all that we can be." – Zig Ziglar'
];
Enter fullscreen mode Exit fullscreen mode

So once we have our quotes array, the next thing we need to define is what we’ll be doing with them.

Let’s recap here — so we want a random quote to be displayed each time that the quote button is clicked. We can do this by applying JavaScript’s onclick() event to the quote button we declared earlier in our JavaScript code.

quoteBtn.onclick = function randomQuote() {
  var rand = quotes[Math.floor(Math.random() * quotes.length)];
  quote.innerHTML = rand;
};
Enter fullscreen mode Exit fullscreen mode

We set quoteBtn.onclick to a function called randomQuote() which will execute the code that will generate our random quotes.

Within out randomQuote() function, we’ll create a variable called rand (which is short for random) and set this equal to the equation you see above.

The equation will take the quotes variable, which stores our array of quotes, and multiply it by a random number. To generate a random number, we’ll be using the Math.random() method (which outputs a random number between 0 and 1) and multiplying this by the number of quotes in our quote variable by using quotes.length. Wrapped around the math.random() multiplied by quotes.length is the math.floor() method which will round the number to the nearest integer thus giving us a whole number to work with.

The last thing to do is to set the rand variable equal to the innerHTML of the quote display, which we declared earlier on and has the variable name quote.

This is the final outcome of our work:

And we’re done! I hope you enjoyed this tutorial, maybe even learned a thing or two?

Get creative with this tutorial! Push yourself and see what you can add using what you’ve learned here as a base. Play around with different shapes colors and fonts. Add other features to the quote-generator! A night/day feature is just the beginning. Here’s a few features to get you started:

  • Add a language feature that allows you to translate the text
  • Change the text color or background-color of something for each random quote
  • Add the ability to share the quote on social media
  • Add the ability to change font-size for increased accessibility
  • Add different categories of quotes the user can choose from

Again, these are only a few ideas to get you started. I’m sure you’ll have even better ones!

For easy access, I have gathered the pens in this tutorial and put them in a collection on Codepen. You can check it out here.

I’d love to see what you come up with so do @ me on Twitter!

I hope you enjoyed this tutorial! If you did, ❤️, 💬 and share! Till next time! ✌️

Top comments (11)

Collapse
 
straleb profile image
Strahinja Babić

Really a nice and creative!!! Is that the part of the freeCodeCamp challenge ?

Collapse
 
munamohamed94 profile image
Muna Mohamed

Thank you! Yup, building a random quote machine is one of the freecodecamp projects

Collapse
 
straleb profile image
Strahinja Babić

Yeah cause i did it as well :) so was just confirming :) Now when i see yours i realize i should have put more effort into mine as :'D

Thread Thread
 
munamohamed94 profile image
Muna Mohamed

Ahh, the beauty of it all is - no time like the present! :-D

Collapse
 
bc7 profile image
Brian

Nice read! I did the quote generator challenge as well, although my css and styling abilities are not on par even for something as simple and neat as this. :)

Collapse
 
munamohamed94 profile image
Muna Mohamed

Thank you Brian, I'm glad you enjoyed the post! And thank you for your kind words! The main purpose of this post is to get the creative juices flowing - I'm sure you can come up with something even better! :)

Collapse
 
ben profile image
Ben Halpern

Fun!

Collapse
 
isaacleimgruber profile image
IsaacLeimgruber

Meeeehh I thought it was a deep learning project to generate inspirational sentences

Collapse
 
munamohamed94 profile image
Muna Mohamed

Sorry to disappoint but this isn't the deep learning project you were looking for. But since you were here already, I hope you enjoyed this post nonetheless. :)

Collapse
 
isaacleimgruber profile image
IsaacLeimgruber

Yeah of course, you probably just gave me an interesting idea for a side project :)

Thread Thread
 
munamohamed94 profile image
Muna Mohamed

Awesome! I'm glad to hear that! :D