How to create a Random Facts Generator with HTML, CSS, and JavaScript

How to create a Random Facts Generator with HTML, CSS, and JavaScript

How to create a Random Facts Generator with HTML, CSS, and JavaScript

Do you want to add an engaging element to your website? A random facts generator is a fantastic way to entertain and educate your audience. In this guide, we’ll walk through the steps to create your own using HTML, CSS, and JavaScript.And it’s very easy I provided every code just copy and paste to use it. Read this article completely.

Setting Up the Basics

Let’s start by structuring the project. Create three files: `index.html`, `styles.css`, and `script.js`. The HTML file will contain the structure of our page, CSS for styling, and JavaScript for functionality.

HTML Structure

In your `index.html` file, define the basic structure of your page. Here’s a simple example:

“`html

<!DOCTYPE html>

<html>

<head>

    <title>Random Facts Generator</title>

    <link rel=”stylesheet” href=”styles.css”>

</head>

<body>

    <h1>Random Facts Generator</h1>

    <div class=”fact-box”>

        <p id=”fact”></p>

        <button onclick=”generateFact()”>

            <span class=”button-icon”>😃</span>

            Generate Fact

        </button>

        <button onclick=”shareFact()”>

            <span class=”button-icon”>📤</span>

            Share Fact

        </button>

    </div>

    <script src=”script.js”></script>

</body>

</html>

“`

Styling with CSS

Next, let’s add some styles to our generator. In the `styles.css` file:

“`css

body {

    text-align: center;

    padding: 40px;

    font-family: Arial, sans-serif;

}

h1 {

    color: #333;

    font-size: 24px;

    margin-bottom: 20px;

    text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);

}

.fact-box {

    width: 90%;

    max-width: 500px;

    margin: 0 auto;

    padding: 20px;

    background-color: #fff;

    border-radius: 8px;

    box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);

    transition: transform 0.3s ease-in-out;

}

.fact-box:hover {

    transform: scale(1.05);

}

p {

    font-size: 20px;

    margin-bottom: 40px;

    color: #333;

    animation: fade-in 0.5s ease-in-out;

}

button {

    padding: 15px 30px;

    background-color: #4CAF50;

    color: white;

    font-size: 20px;

    border: none;

    cursor: pointer;

    margin-top: 20px;

    border-radius: 8px;

    display: flex;

    align-items: center;

    justify-content: center;

    transition: background-color 0.3s;

    box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.3);

}

button:hover {

    background-color: #45a049;

}

.button-icon {

    margin-right: 10px;

}

/* Media Queries */

@media (max-width: 768px) {

    h1 {

        font-size: 20px;

    }

    p {

        font-size: 18px;

    }

    .fact-box {

        padding: 10px;

    }

}

/* Animation */

@keyframes fade-in {

    0% {

        opacity: 0;

    }

    100% {

        opacity: 1;

    }

}

“`

JavaScript Magic

Now, the fun part! In `script.js`, let’s add the functionality:

“`javascript

var facts = [

    “Falling in love has a similar neurological effect on the brain as being addicted to drugs.”,

    “Holding hands with someone you love can reduce stress and lower blood pressure.”,

    “Kissing releases endorphins, which are the body’s natural feel-good chemicals.”,

    “The heart symbol, often associated with love, is thought to resemble the shape of a woman’s buttocks in ancient Greece.”,

    “The tradition of giving engagement rings dates back to ancient Rome.”

];

function generateFact() {

    var factElement = document.getElementById(“fact”);

    var randomFact = getRandomFact();

    factElement.style.animation = “none”; // Reset animation

    factElement.offsetHeight; // Trigger reflow to restart animation

    factElement.style.animation = null;

    factElement.textContent = randomFact;

}

function getRandomFact() {

    var lastFact = localStorage.getItem(“lastFact”);

    var randomFact;

    do {

        randomFact = facts[Math.floor(Math.random() * facts.length)];

    } while (randomFact === lastFact);

    localStorage.setItem(“lastFact”, randomFact);

    return randomFact;

}

function shareFact() {

    var fact = document.getElementById(“fact”).textContent;

    var url = window.location.href; // Replace with your desired website URL

    if (navigator.share) {

        navigator.share({

            title: ‘Random Fact’,

            text: fact + ‘ ‘ + url,

        })

        .then(() => console.log(‘Fact shared successfully.’))

        .catch((error) => console.log(‘Error sharing fact:’, error));

    } else {

        console.log(‘Web Share API not supported.’);

        // You can provide an alternative sharing mechanism for unsupported platforms.

    }

}

// Refresh fact every 30 seconds

setInterval(generateFact, 30000);

“`

Final Touches and Customization

Customize the `facts` array with your own fascinating tidbits. Feel free to add images, additional styling, or expand the functionality to cater to your audience’s interests.

Complete Code

<!DOCTYPE html>

<html>

<head>

    <title>Random Facts Generator</title>

    <style>

        body {

            text-align: center;

            padding: 40px;

            font-family: Arial, sans-serif;

        }

        h1 {

            color: #333;

            font-size: 24px;

            margin-bottom: 20px;

            text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.3);

        }

        .fact-box {

            width: 90%;

            max-width: 500px;

            margin: 0 auto;

            padding: 20px;

            background-color: #fff;

            border-radius: 8px;

            box-shadow: 0px 4px 8px rgba(0, 0, 0, 0.1);

            transition: transform 0.3s ease-in-out;

        }

        .fact-box:hover {

            transform: scale(1.05);

        }

        p {

            font-size: 20px;

            margin-bottom: 40px;

            color: #333;

            animation: fade-in 0.5s ease-in-out;

        }

        button {

            padding: 15px 30px;

            background-color: #4CAF50;

            color: white;

            font-size: 20px;

            border: none;

            cursor: pointer;

            margin-top: 20px;

            border-radius: 8px;

            display: flex;

            align-items: center;

            justify-content: center;

            transition: background-color 0.3s;

            box-shadow: 0px 2px 4px rgba(0, 0, 0, 0.3);

        }

        button:hover {

            background-color: #45a049;

        }

        .button-icon {

            margin-right: 10px;

        }

        /* Media Queries */

        @media (max-width: 768px) {

            h1 {

                font-size: 20px;

            }

            p {

                font-size: 18px;

            }

            .fact-box {

                padding: 10px;

            }

        }

        /* Animation */

        @keyframes fade-in {

            0% {

                opacity: 0;

            }

            100% {

                opacity: 1;

            }

        }

    </style>

</head>

<body>

    <h1>Random Facts Generator</h1>

    <div class=”fact-box”>

        <p id=”fact”></p>

        <button onclick=”generateFact()”>

            <span class=”button-icon”>😃</span>

            Generate Fact

        </button>

        <button onclick=”shareFact()”>

            <span class=”button-icon”>📤</span>

            Share Fact

        </button>

    </div>

    <script>

        var facts = [

            “Falling in love has a similar neurological effect on the brain as being addicted to drugs.”,

            “Holding hands with someone you love can reduce stress and lower blood pressure.”,

            “Kissing releases endorphins, which are the body’s natural feel-good chemicals.”,

            “The heart symbol, often associated with love, is thought to resemble the shape of a woman’s buttocks in ancient Greece.”,

            “The tradition of giving engagement rings dates back to ancient Rome.”

        ];

        function generateFact() {

            var factElement = document.getElementById(“fact”);

            var randomFact = getRandomFact();

            factElement.style.animation = “none”; // Reset animation

            factElement.offsetHeight; // Trigger reflow to restart animation

            factElement.style.animation = null;

            factElement.textContent = randomFact;

        }

        function getRandomFact() {

            var lastFact = localStorage.getItem(“lastFact”);

            var randomFact;

            do {

                randomFact = facts[Math.floor(Math.random() * facts.length)];

            } while (randomFact === lastFact);

            localStorage.setItem(“lastFact”, randomFact);

            return randomFact;

        }

        function shareFact() {

            var fact = document.getElementById(“fact”).textContent;

            var url = window.location.href; // Replace with your desired website URL

            if (navigator.share) {

                navigator.share({

                    title: ‘Random Fact’,

                    text: fact + ‘ ‘ + url,

                })

                .then(() => console.log(‘Fact shared successfully.’))

                .catch((error) => console.log(‘Error sharing fact:’, error));

            } else {

                console.log(‘Web Share API not supported.’);

                // You can provide an alternative sharing mechanism for unsupported platforms.

            }

        }

        // Refresh fact every 30 seconds

        setInterval(generateFact, 30000);

    </script>

</body>

</html>

Video Tutorial

Conclusion

Creating a random facts generator using HTML, CSS, and JavaScript is a fun way to engage your website visitors. By following these steps, you can add an interactive and educational element to your web presence.

So, unleash your creativity, share interesting facts, and captivate your audience with a personalized random facts generator on your website!