In order to have JavaScript showcase a random word from a list when a button is clicked and then display it in a heading 3, follow these steps:

How can I create a JavaScript function that displays a random word from a list when a button is clicked and prints it in a heading 3? I would appreciate a quick response.

//Start of Js code

let display = document.getElementById("motivato");
console.log(display)

var motivation = [{
quote: "Planting popcorn does not produce more popcorn",
person: "Farmer Ted"
}, {
quote: "White whale, bad whale",
person: "Confucious (Moby Dick)"
}, {
quote: "Use the strobe function to disorientate your attacker",
person: "Flashlight"
}, {
quote: "Apply liberally to your erogenous zones",
person: "Spice Bomb"
}, {
quote: "Help me, I'm bleaching",
person: "The Great Barrier Reef"
}];

function motivateMe() {
  var listLength =  Object.keys(motivation).length;
  var randVal = Math.floor(Math.random() * listLength);
  document.write(motivation[randVal]);
  display.innerHTML = motivation;
}

Please help me refine the code and respond below

Thank you

Answer №1

Assuming you're looking for a random quote and not just a single word, here is the solution:

const quotes = [{
        quote: "Don't cry because it's over, smile because it happened",
        author: "Dr. Seuss"
    }, {
        quote: "In three words I can sum up everything I've learned about life: it goes on",
        author: "Robert Frost"
    }, {
        quote: "The only way to do great work is to love what you do",
        author: "Steve Jobs"
    }, {
        quote: "Life is what happens when you're busy making other plans",
        author: "John Lennon"
    }, {
        quote: "Be yourself; everyone else is already taken",
        author: "Oscar Wilde"
}];

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

console.log(quotes[randomNumber]);

const generateQuote = () => {
  const quote = quotes[randomNumber].quote;
    document.getElementById("randomQuote").innerHTML = quote;
}
<p id="randomQuote">The random quote will display here.</p>

<button onclick="generateQuote()">Get Quote</button>

Answer №2

const display = document.getElementById("motivato");

const motivation = [{
  quote: "Planting popcorn does not produce more popcorn",
  person: "Farmer Ted"
}, {
  quote: "White whale, bad whale",
  person: "Confucious (Moby Dick)"
}, {
  quote: "Use the strobe function to disorientate your attacker",
  person: "Flashlight"
}, {
  quote: "Apply liberally to your erogenous zones",
  person: "Spice Bomb"
}, {
  quote: "Help me, I'm bleaching",
  person: "The Great Barrier Reef"
}];

let previousQuote = ""; // Variables to store the previous quote
function motivateMe() {
  const listLength = motivation.length;
  let randVal = motivation[Math.floor(Math.random() * listLength)];
  while(randVal.quote === previousQuote) { // Ensure new quote is different from the previous one
    randVal = motivation[Math.floor(Math.random() * listLength)];
  }
  previousQuote = randVal.quote; // Update previous quote
  display.innerHTML = `<q>${randVal.quote}</q><br><br><small>${randVal.person}</small>`;
}
<button onclick="motivateMe()">Motivate me!</button>
<h3 id="motivato"></h3>

After making this edit, pressing the button will now show a different quote each time, preventing it from appearing unresponsive when the same quote is repeated.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error found in Twitter Bootstrap popover plugin: `this.isHTML` function is missing

I took the example directly from their website: http://jsfiddle.net/D2RLR/631/ ... and encountered the following error: this.isHTML is not a function [Break On This Error] $tip.find('.popover-title')[this.isHTML(title) ? 'html&apos ...

Issue with Bootstrap Nav Pills only functioning properly for the initial option

When using Bootstrap nav pills, only the first one seems to work properly in my case. Even though I have inserted forms for each nav pill, it only shows a blank page. https://i.sstatic.net/QsL1l.png https://i.sstatic.net/Swmtq.png I have PHP code inside t ...

Assigning a variable in jQuery to a PHP variable that has not been defined can halt the script

Here is the code snippet for a document ready function: $(document).ready(function(){ var id = <?php echo "" ?>; alert('boo'); if(id!=0){ $(' ...

It is not possible to access fields in Firestore using Node.js

Exploring the limits of my Firestore database access with a test function: exports.testfunction = functions.https.onRequest(async (request, response) => { try{ const docRef = firestore.collection("Stocks").doc("Automobile" ...

Eliminate the CSS triggered by a mouse click

Having some difficulty toggling the switch to change the background color. Struggling with removing the applied CSS and getting it to toggle between two different colored backgrounds. Code Sample: <!Doctype html> <html lang="en"> <head> ...

Certain scripts fail to load properly when using Internet Explorer

The code snippet provided only seems to be functional in Firefox, where it displays all alerts and successfully executes the displayUserLanding function. However, in Internet Explorer, the browser appears to only execute the following alert: alert("Helper ...

Div that scrolls independently without affecting the position of other elements

Visit this link for reference <div class="col-10 content" id="content"> <ul> <li>News</li> <li>News</li> <li>News</li> <li>News</li> < ...

A guide on executing multiple Post Requests in Node.js

Currently, I am facing some issues with my code while attempting to make multiple post requests based on certain conditions. The goal is to retrieve data from an online database (Firebase), save it locally, and then delete the online data. Here's wha ...

Issue with Vue 3 where radio input remains unchecked after being clicked

I'm currently facing an issue with radio buttons for answers in my questions. Whenever I click on an answer, the radio input does not stay checked and I am unable to disable the other options. My front-end is developed using Vue 3 and the back-end wit ...

Designing a uniquely shaped button

Is there a way to design a button with a slightly irregular shape? The current CSS for my button creates a basic rectangle like this: .btnclass { width:100; height:40; } However, I would like it to have a more unique appearance such as this: ...

Eliminate a targeted class from an HTML string in PHP

I am dealing with a string that looks like this: $string = '<img class="img-responsive animate scale animated" src="image/catalog/blocks/about-banner.jpg" alt="">'; My goal is to delete the img-responsive class from it. Any suggestions o ...

What is the best method for transferring form data to a string and storing it in localStorage effectively?

Is this the most efficient method for extracting form data into a string and storing it in localStorage? I developed this method independently, but I'm not an experienced programmer. It seems to work for my needs, but I'm unsure if it's com ...

Automatic placement of the cursor at the left end of the username field in the registration form is required

Hey there! I'm looking to customize the registration form on my WordPress website so that when a user clicks on any field, such as the username field, the cursor automatically moves to the left end of that field and the keyboard switches to ENG-US. ...

Looking to attach a listener to an element within a modal once it has finished rendering?

Upon clicking a button, a modal window appears. The controller assigned to the modal contains a list of element IDs that need listeners assigned. However, when the controller initializes, the modal has not yet rendered, causing the elements requiring liste ...

What could be causing my completed torrents to sometimes not be saved to my disk?

Currently, I am working on developing a small torrent client using electron and webtorrent. Although everything appears to be functioning correctly initially, there is an issue where sometimes the resulting files from a finished download are not being save ...

Customized slider in jQuery UI allowing users to select height using a scaled ruler

Currently, I am tackling a challenging math problem related to adjusting the height selector input. Essentially, I have implemented a jQuery UI slider for choosing a height. It operates in inches and ranges from 0 to 120 (equivalent to 10 feet in height). ...

Using Google Fonts in a Typescript React application with JSS: A step-by-step guide

How can I add Google fonts to my JSS for use in styling? const styles = ({palette, typography}: Theme) => createStyles({ time: { flexBasis: '10%', flexShrink: 0, fontSize: typography.pxToRem(20) }, guestname: ...

What is the best way to compare two arrays that have elements of different data types?

Can someone help me compare two arrays in TypeScript to see if they are identical? I'm having trouble with the current code. Here's what I have: let props:(string|boolean)[]=['abc','def',true,false,'xyz'] let propsCo ...

Can responsive images be utilized with a DIV's background-image property?

For my website, I want to incorporate a variety of Thumbnails that are retrieved from a database and displayed in different sizes within a Masonry grid. Typically, I would use background-image:url(image.jpg); background-size: 100% 100%:, but I am aiming t ...

I keep encountering an error with the Next.js Image component, even though I have properly included the src prop

By passing the src prop to the UserCard component, I am encountering the following error message. Error Unhandled Runtime Error Error: Image is missing required "src" property. Make sure you pass "src" in props to the `next/image` comp ...