DEV Community

Cover image for Best Ultimate Guide To Build A Random Quote Generator 2022
Jai Krishna
Jai Krishna

Posted on

Best Ultimate Guide To Build A Random Quote Generator 2022

Hey Everyone 👋, today’s article is aimed at beginners trying to build a random quote generator using JavaScript. This will definitely make you understand the interaction between the frontend and backend and how they work on a web browser.

In my previous post, I had shared about Amazing Text To Speech Converter With HTML, CSS & JavaScript (2021) – RoyalityFree Blog. I received a great response to that, so I thought why not share more of my projects for free 🎉.

Note: I've worked very hard on this project and the output, was making it free 🤗. You can too support me in return for free by stargazing the official repository here.

As for this project, we’ll build a random quote generator that will display a quote fetched from an API on a button click or a default set. To get started, like always you’ll need three essential things that are forever useful for any sort of project:

  • A web browser
  • A code editor
  • A desire boost

For this tutorial, I will use the Microsoft Edge browser, Visual Studio Code as my code editor, and most importantly a boost in my desire to build something till the end! If you don’t seem familiar with my suggestions, feel free to use any other alternative.

Random Quote Generator (Understanding)

A Random Quote Generator is proficient in pulling quotes randomly from an API, any database, or plainly from an array. We will be designing a Random Quote Generator from scratch using HTML, CSS, JavaScript, and free-quotes API.

Image description

Random Quote Generator (Building)

For every project, we need some basic core files. In this case, we’ll need three files with alike extensions, i.e .html, .css, .js. Once you’ve organized them in a folder (e.g random-quote-generator), you are good to paste the source code from the following sections.

Image description

You can optionally download the whole source code of this Random Quote Generator from the available mirrors, at the end of the article.

Firstly, create an HTML file with a filename index.html and paste the following code into your HTML file. Save It, you’ve to create a file with an .html extension at the last.

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<!-- Meta Tags Start, For Reference https://www.w3schools.com/tags/tag_meta.asp -->
<meta charset="utf-8">
<meta name="description" content="Free random quotes generator, either inspirational or motivational.">
<meta name="keywords" content="quotes, random quotes, random quote generator">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="msapplication-TileImage" content="/ms-icon-144x144.png">
<meta name="theme-color" content="#ffffff">
<!-- Meta Tags End-->
<!-- Title (Change This If Publlic)-->
<title>Random Quotes | RoyalityFree</title>
<!-- Link Custom Stylesheet And Fonts Start -->
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css" integrity="sha512-Fo3rlrZj/k7ujTnHg4CGR2D7kSs0v4LLanw2qksYuRlEzO+tcaEPQogQ0KaoGN26/zrn20ImR1DfuLWnOo7aBA==" crossorigin="anonymous" referrerpolicy="no-referrer" />
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Poppins&display=swap" rel="stylesheet">
<!-- Link Custom Stylesheet And Fonts End-->
<body>
<!-- Start Container -->
<div class="wrapper">
<!-- Start Header -->
<header>
    Quote For <span id="getday"></span>
</header>
<!-- End Header -->
<!-- Start Content -->
<div class="content">
<div class="quote-area">
<i class="fas fa-quote-left"></i>
<p class="quote">Protecting your mind, body and spirit from negativity is a sign of self-love.</p>
<i class="fas fa-quote-right"></i>
</div>
<div class="author">
<span>__</span>
<span class="name">Nitin Namdeo</span>
</div>
</div>
<div class="buttons">
<div class="features">
<ul>
<li class="speech"><i class="fas fa-volume-up"></i></li>
<li class="copy" onclick="onCopy()"><i class="fas fa-copy"></i></li>
<li class="twitter"><i class="fab fa-twitter"></i></li>
</ul>
<button>Another</button>
</div>
</div>
</div>
<!-- End Content -->
<!-- Get Script-->
<script src="script.js">
</script>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Secondly, create a CSS file with the filename style.css and paste the following code into the file. Save It, you have to create a file with .css an extension at the last.

/* Built By RoyalityFree | Codes Initiative */
*{
    margin:0;
    padding:0;
    box-sizing:border-box;
    font-family:poppins,sans-serif
}
body{
    display:flex;
    align-items:center;
    justify-content:center;
    min-height:100vh;
    padding:0 10px;
    background-image: radial-gradient(#31e9cb,#a3f5e8,#31e9cb);
    user-select: none;
}
::selection{
    color:#fff;
    background:#1AE78D
}
.wrapper{
    width:605px;
    background:#fff;
    border-radius:15px;
    padding:30px 30px 25px;
    box-shadow:0 12px 35px rgba(0,0,0,.1)
}
header,.content :where(i,p,span){
    color:#102137
}
.wrapper header{
    font-size:35px;
    font-weight:600;
    text-align:center
}
.wrapper .content{
    margin:35px 0
}
.content .quote-area{
    display:flex;
}
.quote-area i{
    font-size:15px
}
.quote-area i:first-child{
    margin:3px 0 0 0
}
.quote-area i:last-child{
    display:flex;
    margin:0 0 3px 10px;
    align-items:flex-end;
}
.quote-area .quote{
    font-size:22px;
    text-align:center;
}
.content .author{
    display:flex;
    font-size:18px;
    margin-top:20px;
    font-style:italic;
    justify-content:flex-end
}
.author span:first-child{
    margin:-6px 5px 0 0;
    font-family:monospace;
}
.buttons .features{
    display:flex;
    margin-top:20px;
    align-items:center;
    justify-content:space-between;
}
.features ul{
    display:flex
}
.features ul li{
    margin:0 5px;
    height:47px;
    width:47px;
    display:flex;
    cursor:pointer;
    color:#1AE78D;
    list-style:none;
    border-radius:50%;
    align-items:center;
    justify-content:center;
    border:2px solid #1AE78D;
    transition:all .3s ease
}
.features ul li:first-child{
    margin-left:0
}
ul li:is(:hover,.active){
    color:#fff;
    background:#1AE78D
}
ul .speech.active{
    pointer-events:none
}
.buttons button{
    border:none;
    color:#fff;
    outline:none;
    font-size:16px;
    cursor:pointer;
    padding:13px 22px;
    border-radius:15px;
    background:#1AE78D
}
.buttons button:hover{
    background: #4DD99C;
}
.buttons button.loading{
    opacity:.7;
    pointer-events:none
}
@media(max-width:728px){
    .wrapper{
        padding:25px 25px 20px;
        margin: 15px 15px 15px 15px;    
    }
    .wrapper header{
        font-size:29px
    }
    .quote-area .quote{
        font-size:20px;
        word-break:keep-all
    }
    .content .author{
        font-size:16px
    }
    .quote-area i{
        font-size:12px
    }
    .features ul li{
        margin:0 3px;
        height:45px;
        width:45px
    }
    .buttons button{
        font-size:15px;
        padding:12px 20px
    }
}
Enter fullscreen mode Exit fullscreen mode

Lastly, create a JavaScript file with a filename script.js and paste the following code into your JavaScript file. Save It, you have to create a file with .js an extension at last.

// Built By RoyalityFree | Codes Initiative

const quoteText = document.querySelector(".quote"),
    quoteBtn = document.querySelector("button"),
    authorName = document.querySelector(".name"),
    speechBtn = document.querySelector(".speech"),
    copyBtn = document.querySelector(".copy"),
    pingTwitter = document.querySelector(".twitter"),
    synth = speechSynthesis;

function randomQuote() {
    quoteBtn.classList.add("loading");
    quoteBtn.innerText = "Loading 🎉";
    fetch("https://free-quotes-api.herokuapp.com/").then(response => response.json()).then(result => {
        quoteText.innerText = result.quote;
        authorName.innerText = result.author || "No Author";
        quoteBtn.classList.remove("loading");
        quoteBtn.innerText = "Another";
    });
}
speechBtn.addEventListener("click", () => {
    if (!quoteBtn.classList.contains("loading")) {
        let utterance = new SpeechSynthesisUtterance(`${quoteText.innerText} by ${authorName.innerText}`);
        synth.speak(utterance);
        setInterval(() => {
            !synth.speaking ? speechBtn.classList.remove("active") : speechBtn.classList.add("active");
        }, 10);
    }
});
copyBtn.addEventListener("click", () => {
    navigator.clipboard.writeText(quoteText.innerText);
});
pingTwitter.addEventListener("click", () => {
    let twitterUrl = `https://twitter.com/intent/tweet?url=${quoteText.innerText}`;
    window.open(twitterUrl, "_blank");
});
quoteBtn.addEventListener("click", randomQuote);

pingTwitter.addEventListener("click", () => {
    let twitterUrl = `https://twitter.com/intent/tweet?url=${quoteText.innerText}`;
    window.open(twitterUrl, "_blank");
});
const d = new Date();
const weekday = new Array(7);
weekday[0] = "Sunday";
weekday[1] = "Monday";
weekday[2] = "Tuesday";
weekday[3] = "Wednesday";
weekday[4] = "Thursday";
weekday[5] = "Friday";
weekday[6] = "Saturday";
let day = weekday[d.getDay()];
document.getElementById("getday").innerHTML = day;
function onCopy() {
    alert("Copied Quote Successfully To 📋!");
  }
Enter fullscreen mode Exit fullscreen mode

With all that set in place, we’re ready to check the output of all three files combined to build a powerful webpage. It should do something like this by now:

Image description

Random Quote Generator (Last Words)

That’s it, you’ve now successfully built a Random Quote Generator Webpage in native HTML, CSS, and JavaScript.

If your code does not work or you have faced any problem/issue, try downloading the source files from the provided download button below.

It’s priceless and a .zip file that will be downloaded and then just extract it to your file manager, server, etc.

Discussion (0)