Генератор случайных цитат с использованием HTML, CSS и JavaScript

В этой статье вы узнаете, как создать генератор случайных цитат (такую программу называют: генератор фраз или генератор случайных фраз или генератор рандомных фраз и т.п.) с использованием HTML, CSS, JavaScript и API. Это приложение выбирает новую случайную цитату из API при нажатии кнопки и отображает ее в браузере. Вот скриншот того, как выглядит готовое приложение:


Наш проект генератора случайных цитат состоит из трех частей: HTML, CSS и JavaScript. Итак, сначала вам нужно создать три файла, первый - это файл HTML (index.html), второй - файл CSS (style.css), а третий - файл JS (index.js).

Часть HTML 

Откройте файл index.html и введите в него следующий код.

<!DOCTYPE html>
<html>
    <head>
        <!--META information-->
        <meta charset="UTF-8">
        <meta name="description" content="Random Quote Generator">
        <meta name="keywords" content="HTML,CSS,JavaScript, Quotes, API">
        <meta name="author" content="Neha Soni">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <!--End of META information-->

        <title>Random Quote Generator</title>

        <!--LINK CUSTOM CSS FILE-->
        <link rel="stylesheet" href="style.css">

        <!--FONTAWESOME CDN-->
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.1/css/all.min.css" integrity="sha512-+4zCK9k+qNFUR5X+cKL9EIR+ZOhtIloNl9GIKS57V1MyNsYpYcUrUeQc9vNfzsWfV28IaLL3i96P9sdNyeRssA==" crossorigin="anonymous" />
    </head>
    <body>
        <!-- Quote Container -->
        <div class="container">
             <!-- Quote to be Displayed Here -->
            <h1>
            <i class="fas fa-quote-left"></i>
            <span class="quote" id="quote"></span>
            <i class="fas fa-quote-right"></i>
            </h1>
            <!-- Author to be Displayed Here -->
            <p class="author" id="author"></p>

            <hr/>
            <div class="buttons">
               <!--Button to tweet the quote -->
                <a class="twitter" id="tweet" href="https://twitter.com/intent/tweet?text=Greetings" data-size="large" target="_blank" rel="noopener noreferrer"><i class="fab fa-twitter"></i></a>

                <!--Add an onclick event on 'next quote' button. Upon the click of a button, a new random quote is generated-->
                <button class="next" onclick="getNewQuote()">Next quote</button>
            </div>
        </div>

        <!--LINK CUSTOM JS FILE-->
        <script src="script.js"></script>
    </body>
</html>

Часть CSS

style.css

*{
    margin:0;
    padding:0;
    box-sizing: border-box;
}

body{
    min-height:100vh;
    transition: 0.5s;
    transition-timing-function: ease-in;
    background-image: linear-gradient(to right bottom, #ff8080, #ffedbca8);
    display: flex;
    align-items: center;
    justify-content: center;

}

.container
{
    display: flex;
    flex-direction: column;
    align-items: center;
    padding: 30px;
    box-shadow: 0 4px 10px rgba(0, 0, 0, 0.6);
    border-radius: 15px;
    width: 600px;
    background-color: rgba(255, 255, 255, 0.3);
    margin: 10px;

}
.fa-quote-left, .fa-quote-right {
    font-size: 35px;
    color: #b30000;
}
.quote
{
    text-align: center;
    font-size: 40px;
    font-weight: bold;
}
.author 
{

    margin:10px;
    text-align: right;
    font-size: 25px;
    font-style: italic;
    font-family: cursive;
}
hr {
    margin: 10px 0;
    width: 100%;
    border: 1px solid black;
    background-color: black;
}
.buttons {
    width: 100%;
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 9px;
}
.twitter
{
    border:1px solid #66b3ff;
    border-radius: 4px;
    background-color: #66b3ff;
    color: white;
    text-align: center;
    font-size: 1.8em;
    width: 60px;
    height: 35px;
    line-height: 40px;
}
.next
{
    font-size:18px;
    border-radius: 5px;
    cursor:pointer;
    padding: 10px;
    margin-top: 5px;
    font-weight: bold;
    color: white;
    background-image: linear-gradient(to right bottom, #e60000, #ffedbca8);
}
.container:hover
{
    box-shadow: 0 10px 10px #e60000;
}

Часть JavaScript

А теперь подошла к концу основная и последняя часть нашего приложения-генератора случайных цитат. Весь код для работы приложения написан в функции getNewQuote (). В этой функции мы будем получать данные из API. Поскольку получение данных из API - это асинхронный процесс, мы будем использовать функцию async для извлечения данных и сохранения их в массиве.
Узнайте больше об асинхронной функции JavaScript здесь.

Обсудим все пошагово: -

Шаг 1: - Создайте функцию getNewQuote ().

Шаг 2: - Сохраните API в переменной url и извлеките из нее данные с помощью метода fetch (). Теперь метод fetch () возвращает обещание, для его обработки мы используем ключевое слово await. Как только обещание будет разрешено, сохраните данные в переменной ответа.

Шаг 3: - Преобразуйте ответ в формат JSON, и он также возвращает обещание, поэтому нам снова нужно добавить ключевое слово await для обработки обещания, и всякий раз, когда обещание будет разрешено, мы будем сохранять данные в массиве allQuotes.

Шаг 4: - В JavaScript есть полезные встроенные функции: Math.floor () и Math.random (). Мы будем использовать метод Math.random () для генерации числа от 0 до общего количества цитат, полученных из API (длина массива allQuotes), и метод Math.floor () для округления числа ВНИЗ до ближайшего целого числа. Теперь с помощью этого числа мы сможем получить доступ к одному объекту из массива.

Шаг 5: - Каждый элемент, хранящийся в массиве, представляет собой объект, у которого есть текст свойства и автор. Сохраните цитату, присутствующую в случайно сгенерированном индексе, а также сохраните автора соответствующей цитаты.

Шаг 6: - Делаем автора анонимным, если автор не присутствует и когда значения готовы, давайте отобразим его в элементах HTML, которые мы создали ранее. Это делается путем их получения с помощью метода document.getElementById и вставки значений внутри него с помощью свойства innerHTML.

Шаг 8: - Вызовите функцию getNewQuote () в конце, чтобы запустить функцию при точной перезагрузке страницы.

Полный код javascript

index.js

const text=document.getElementById("quote");
const author=document.getElementById("author");
const tweetButton=document.getElementById("tweet");

const getNewQuote = async () =>
{
    //api for quotes
    var url="https://type.fit/api/quotes";    

    // fetch the data from api
    const response=await fetch(url);
    console.log(typeof response);
    //convert response to json and store it in quotes array
    const allQuotes = await response.json();

    // Generates a random number between 0 and the length of the quotes array
    const indx = Math.floor(Math.random()*allQuotes.length);

    //Store the quote present at the randomly generated index
    const quote=allQuotes[indx].text;

    //Store the author of the respective quote
    const auth=allQuotes[indx].author;

    if(auth==null)
    {
        author = "Anonymous";
    }

    //function to dynamically display the quote and the author
    text.innerHTML=quote;
    author.innerHTML="~ "+auth;

    //tweet the quote
    tweetButton.href="https://twitter.com/intent/tweet?text="+quote+" ~ "+auth;
}
getNewQuote();


Вы только что создали генератор случайных цитат. 

Использованные источники

  1. Neha Soni. Random Quote Generator Using HTML, CSS, and JavaScript. 23 may 2021. URL:https://dev.to/nehasoni__/random-quote-generator-using-html-css-and-javascript-3gbp

  2. Генератор цитат — слова великих философов и не только! ezrandom.com. URL:ezrandom.com/sluchajnaya-czitata-generator.html

Я сотрудник Я абитуриент Я студент