JavaScript Coding Exercise Random quote generator

Random quote generator

Example of a random quote generator using HTML, CSS, and JavaScript.

HTML:

<!DOCTYPE html>

<html>

<head>

<meta charset=”utf-8″>

<title>Random Quote Generator</title>

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

</head>

<body>

<div class=”container”>

<h1>Random Quote Generator</h1>

<p id=”quote”></p>

<button id=”btn”>Generate Quote</button>

</div>

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

</body>

</html>

In this HTML code, we have created a simple structure for our random quote generator. We have a container with a heading, a paragraph element with an ID of “quote”, and a button with an ID of “btn”. We have also linked our CSS and JavaScript files in the head and body sections respectively.

CSS:

.container {

margin: 0 auto;

max-width: 600px;

padding: 20px;

text-align: center;

}

h1 {

font-size: 36px;

margin-bottom: 20px;

}

#quote {

font-size: 24px;

margin-bottom: 20px;

}

button {

background-color: #4CAF50;

border: none;

color: white;

padding: 12px 24px;

text-align: center;

font-size: 16px;

cursor: pointer;

border-radius: 4px;

}

In this CSS code, we have defined some basic styles for our random quote generator. We have set the container to have a max-width of 600px, centered it on the page, and aligned the text to the center. We have also defined styles for the heading, quote, and button elements.

JavaScript:

const quotes = [

{

quote: “Be yourself; everyone else is already taken.”,

author: “Oscar Wilde”

},

{

quote: “Two things are infinite: the universe and human stupidity; and I’m not sure about the universe.”,

author: “Albert Einstein”

},

{

quote: “In three words I can sum up everything I’ve learned about life: it goes on.”,

author: “Robert Frost”

},

{

quote: “If you tell the truth, you don’t have to remember anything.”,

author: “Mark Twain”

},

{

quote: “To be yourself in a world that is constantly trying to make you something else is the greatest accomplishment.”,

author: “Ralph Waldo Emerson”

}

];

const btn = document.getElementById(‘btn’);

const quote = document.getElementById(‘quote’);

function generateQuote() {

const randomIndex = Math.floor(Math.random() * quotes.length);

quote.innerHTML = ‘”‘ + quotes[randomIndex].quote + ‘”‘ + ‘ – ‘ + quotes[randomIndex].author;

}

btn.addEventListener(‘click’, generateQuote);

In this JavaScript code, we have defined an array of quotes and authors, and then created a function to generate a random quote from the array when the button is clicked. We have used the Math.floor and Math.random methods to generate a random index within the length of the quotes array, and then used that index to access a random quote and author from the array. We have also added an event listener to the button to trigger the generateQuote function when it is clicked.

Overall, this code will display a random quote and author from the quotes array each time the “Generate Quote” button is clicked.