{}const=>[]async()letfn</>var
WebPractice

Random quote generator in HTML, CSS and JavaScript

Learn how to create a random quote generator using HTML, CSS, and JavaScript. A complete guide for beginners: creating, styling, and programming an application from scratch. Use the ready-made code and improve your web development skills!

К

Kodik

Author

5 min read

💡 Random quote generator in HTML, CSS, and JavaScript

In this article, we'll look at how to create a simple random quote generator using HTML, CSS, and JavaScript. ✨ This is a great project for beginners to practice using all three technologies at the same time. By the end of the article, you will have a ready-made application that generates random quotes, allows you to copy, voice, and share them on Twitter. Let's get started!

Project demo | 📂 Download source code on GitHub

🤖 In the app Code you can learn HTML, CSS and JavaScript, as well as many other courses to start your journey in web development! 🌱

🛠️ Preparation

Before you start writing code, make sure you have the following:

  1. 🗒️ Code editor: You can use any text editor, but I recommend Visual Studio Code, as it is convenient and has many useful extensions.

  2. 🛈 Browser: Any modern browser, such as Chrome or Firefox, to test your application.

  3. 📘 Basic knowledge of HTML, CSS and JavaScript: It is advisable to have basic knowledge to make it easier to understand the project, but you can also follow this article even without preparation.

Now that you're ready, let's start creating our project from a blank HTML file! 🌱

🔥 100,000+ students already with us

Tired of reading theory?
Time to code!

Kodik — an app where you learn to code through practice. AI mentor, interactive lessons, real projects.

🤖 AI 24/7
🎓 Certificates
💰 Free
🚀 Start learning
Joined today

🗃️ Step 1: Creating HTML

HTML is the basis of our application. Let's create a file index.html, in which we will describe the structure of the future quote generator:

<!DOCTYPE html>
<html lang="ru">
<head>
  <meta charset="utf-8">
  <title>Генератор случайных цитат | Coursme</title>
  <link rel="stylesheet" href="style.css">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"/>
</head>
<body>
  <div class="wrapper">
    <header>Цитата дня</header>
    <div class="content">
      <div class="quote-area">
        <i class="fas fa-quote-left"></i>
        <p class="quote">Никогда не сдавайтесь, потому что вы никогда не знаете, может быть, следующая попытка окажется успешной.</p>
        <i class="fas fa-quote-right"></i>
      </div>
      <div class="author">
        <span>__</span>
        <span class="name">Мэри Кэй Эш</span>
      </div>
    </div>
    <div class="buttons">
      <div class="features">
        <ul>
          <li class="speech"><i class="fas fa-volume-up"></i></li>
          <li class="copy"><i class="fas fa-copy"></i></li>
          <li class="twitter"><i class="fab fa-twitter"></i></li>
        </ul>
        <button>Новая цитата</button>
      </div>
    </div>
  </div>
  <script src="script.js"></script>
</body>
</html>

In this file, we created the main framework of our application. It contains a title, an area to display the quote and the author, and buttons for interaction.

🖼️ Step 2: Styling with CSS

Now let's make our app beautiful! To do this, we use CSS. Let's create a style.css file and add styles:

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600;700&display=swap');
*{
  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;
  background: #5372F0;
}
.wrapper{
  width: 605px;
  background: #fff;
  border-radius: 15px;
  padding: 30px 30px 25px;
  box-shadow: 0 12px 35px rgba(0,0,0,0.1);
}
header{
  font-size: 35px;
  font-weight: 600;
  text-align: center;
}
.quote{
  font-size: 22px;
  text-align: center;
}
.author{
  font-size: 18px;
  font-style: italic;
  text-align: right;
}
button{
  border: none;
  color: #fff;
  padding: 13px 22px;
  background: #5372F0;
  border-radius: 30px;
  cursor: pointer;
}

We added styles for a convenient and pleasant interface: we changed the font, set the background, and added styles for buttons and text.

💡 Step 3: Add logic with JavaScript

Now it's time to add functionality to our application using JavaScript. Let's create a file script.js and add the following code:

// Getting all the necessary DOM elements
const quoteText = document.querySelector(".quote"),
    quoteBtn = document.querySelector("button"),
    authorName = document.querySelector(".name"),
    speechBtn = document.querySelector(".speech"),
    copyBtn = document.querySelector(".copy"),
    twitterBtn = document.querySelector(".twitter"),
    synth = speechSynthesis;

// Function to get a random quote
function randomQuote() {
    quoteBtn.classList.add("loading");
    quoteBtn.innerText = "Loading Quote...";

    fetch("https://api.forismatic.com/api/1.0/?method=getQuote&format=json&lang=ru")
        .then(response => response.json())
        .then(result => {
            quoteText.innerText = result.quoteText;
            authorName.innerText = result.quoteAuthor || "Unknown author";
            quoteBtn.classList.remove("loading");
            quoteBtn.innerText = "New quote";
        });
}

// Events for buttons
speechBtn.addEventListener("click", () => {
    if (!quoteBtn.classList.contains("loading")) {
        let utterance = new SpeechSynthesisUtterance(`${quoteText.innerText} from ${authorName.innerText}`);
        synth.speak(utterance);
    }
});

copyBtn.addEventListener("click", () => {
    navigator.clipboard.writeText(quoteText.innerText);
});

twitterBtn.addEventListener("click", () => {
    let tweetUrl = `https://twitter.com/intent/tweet?url=${quoteText.innerText}`;
    window.open(tweetUrl, "_blank");
});

quoteBtn.addEventListener("click", randomQuote);

🧐 Explanation of methods

  1. Getting all the necessary DOM elements:

    • quoteText: Link to the element where the quote text will be displayed.

    • quoteBtn: Link to the button to generate a new quote.

    • authorName: Link to the element that displays the name of the quote author.

    • speechBtn, copyBtn, twitterBtn: Links to buttons for voicing quotes, copying and posting on Twitter, respectively.

    • synth: We use the browser's speech synthesis API to voice quotes.

  2. randomQuote(): This function makes a request to the API to get a random quote and displays it in the application. While the quote is loading, the button becomes inactive, and the button text changes to "Loading Quote...".

  3. Events for buttons:

    • Voiceover quote (▶️): When you click on the quote sound button, the SpeechSynthesisUtterance object is created, which sounds the current quote using speech synthesis.

    • Copying a quote (📋): Copies the text of the current quote to the user's clipboard using navigator.clipboard.writeText().

    • Twitter post (🔗): Opens a window for posting the current quote on Twitter, creating a URL for a tweet with the quote text.

    • New quote: Pressing the button calls the randomQuote() function to load a new quote.

💖 Results

We created a simple random quote generator using HTML, CSS, and JavaScript. ✨ This project helped us combine our knowledge of layout and programming, as well as work with the API. Now you can expand it by adding more features, such as saving your favorite quotes or even creating your own list of quotes. Good luck and inspiration in your further study of web development! 🌱

You can use this project as a basis for creating more complex games or even expand the functionality of this game. For example, add a win counter, improve the graphics, or make the game multiplayer. The possibilities are endless, and it all depends on your imagination and creativity!

For the full source code and possibly additional improvements, check out our GitHub.

If you have any questions, don't hesitate to ask. Good luck in programming, and may your projects always be as interesting and exciting! 👊🌟

🎯Stop procrastinating

Liked the article?
Time to practice!

In Kodik, you don't just read — you write code immediately. Theory + practice = real skills.

Instant practice
🧠AI explains code
🏆Certificate

No registration • No card