What is the process for invoking a property with a random approach?

I'm currently working on creating a quote generator using an object instead of an array.

Although I can retrieve results, I seem to be getting the name of the quote rather than the actual quote itself.

I attempted to use the bind method, but unfortunately, it didn't yield any results.

Would appreciate any assistance with this issue. Thank you!

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <title>Quote Generator</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

    <link rel="stylesheet" href="style.css">
</head>

<body>

    <div class="text-center">
        <div class="background">
            <h1>2018 Reading Notes</h1>
            <p>Motivational Quotes</p>
        </div>
        <p id="quotes"></p>
        <button class='btn btn-danger mt-4' style="border-radius: 0px; font-size: 2rem;">Show me another Quote</button>
        <p class="mt-5">Made with ❤️️ by Anthony</p>
    </div>


    <script src="jquery-3.3.1.min.js"></script>
    <script src="script.js"></script>
</body>

</html>

var paragraph = document.querySelector('#quotes');
var buttonGenerator = document.querySelector('.btn');

var quotes = {
    quote1: {
        author: 'Carol Burnett',
        quote: 'Only I can change my life. No one can do it for me.'
    },
    quote2: {
        author: 'Norman Vaughan',
        quote: 'Dream Big and Date to Fail.'
    },
    quote3:{
        author:'Jean-Claude Van Damme',
        quote:'I now truly believe it is impossible for me to make a bad movie.'
    }

}

buttonGenerator.addEventListener('click', quoteGenerator);

function quoteGenerator(){
    var count = 0;
    for(var value in quotes){
        if(Math.random() < 1/count++)
        paragraph.innerHTML = quotes[value].quote;
       console.log(quotes[value].quote);
    }
}

Answer №1

It appears I overlooked your preference to not use an array, but that would be the ideal approach. Please refer below for guidance.

To implement this solution, create an array of quotes as shown in the snippet. Insert the JavaScript code within <script></script> tags after the </body> tag

var paragraph = document.querySelector('#quotes');
var buttonGenerator = document.querySelector('.btn');

var quotes = [
    {
        author: 'Carol Burnett',
        quote: 'Only I can change my life. No one can do it for me.'
    },
    {
        author: 'Norman Vaughan',
        quote: 'Dream Big and Dare to Fail.'
    },
    {
        author:'Jean-Claude Van Damme',
        quote:'I now truly believe it is impossible for me to make a bad movie.'
    }

]


buttonGenerator.addEventListener('click', quoteGenerator);

function quoteGenerator(){
    var item = quotes[Math.floor(Math.random()*quotes.length)];
console.log(item.author);
console.log(item.quote);
paragraph.innerHTML = 'Author:<br />' + item.author + '<br /><br />Quote:<br />' + item.quote;
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8>
    <title>Quote Generator</title>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css">

    <link rel="stylesheet" href="style.css">
</head>

<body>

    <div class="text-center">
        <div class="background">
            <h1>2018 Reading Notes</h1>
            <p>Motivational Quotes</p>
        </div>
        <p id="quotes"></p>
        <button class='btn btn-danger mt-4' style="border-radius: 0px; font-size: 2rem;">Show me another Quote</button>
        <p class="mt-5">Made with ❤️️ by Anthony</p>
    </div>


    <script src="jquery-3.3.1.min.js"></script>
    <script src="script.js"></script>
</body>

</html>

Answer №2

It's a bit unclear why you're attempting to utilize an object in this scenario, but if necessary, Object.keys(quotes) could be helpful as it provides the actual keys (such as 'quote1', 'quote2', etc.) of your object as an array. Afterwards, generating a random number allows you to retrieve the corresponding index from the array and use that string to access the object properties.

var array = Object.keys(quotes); // convert the object to an array of its keys
var key = array[randomIndex]; // obtain a random key
var quoteObject = quotes[key]; // utilize it for accessing the property of the object.

(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys)

Nevertheless, using an array is always recommended in this situation, if possible.

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

jQuery Mobile: issue with positioning an external panel on the right side

I am looking to incorporate an external header and two external panels, one on the left and one on the right. The challenge is to ensure that these panels remain visible at all times on larger screens. I encountered some difficulties positioning the panel ...

Redirecting in PHP after an AJAX request is made

I'm trying to figure out how to redirect to another page in PHP code within an AJAX call. I've searched online and found suggestions to use JavaScript like window.location.href = 'url';, but it doesn't seem to be working for me. W ...

Is there a way to implement tooltips on an element that has text-ellipsis enabled?

I am facing an issue with displaying an account number that exceeds 100 characters. I need to restrict the display with overflow hidden while still being able to show the full account number using a tooltip. Below is the code snippet: <span class="tex ...

Encountering an error with dynamic routing in Angular 4 when using dynamic components

Upon receiving routing configuration from a server and loading it before the application bootstrap, the config.json file contains the following setup: [{ "path": "dashboard", "component": "SingleComponent", "data": {...} }, { "path": "payment", ...

While the file does exist in the current directory, the `readFileSync` function is unable to locate

For my latest SvelteKit project, I was developing a Joke API using Bun as the runtime and TypeScript as the programming language. The goal of this API was to fetch one random dad joke from a text file that contained 363 jokes. Everything was going smoothly ...

Creating captchas seems like a mistake in reasoning to me

I am encountering an issue with my code. I created a basic newbie-level captcha using Javascript. Below is the code snippet: <!DOCTYPE html> <html> <head> <style> </style> </head> <body> <h1>T ...

Revolutionary custom binding with Bootstrap popover integration

Utilizing asp.net mvc with dynamic knockout columns, I am facing an issue with one of the column headers named "Status". The desired functionality includes a bootstrap popover that displays information when a user clicks a font-icon question mark. Here is ...

Button click not functioning to switch the displayed image in Javascript

As a beginner in Javascript, I'm attempting to create a basic button in html that switches the originally shown image when clicked. Unfortunately, my current code isn't functioning properly. Could someone please assist me in identifying the mista ...

I am unable to implement code coverage for Cypress in Debian at the moment

Having trouble obtaining code coverage results using Cypress in my Virtual Machine (Debian Bullseye), but no issues when I run the same project on my Windows machine. On Linux, the code coverage shows up as: Click here to view Index.html inside lcov-repor ...

Is there a way to extract data within xml tags with attributes using JavaScript/ Ionic without relying on DOM or ActiveXObject?

I am trying to extract specific information located between two tags, specifically <wsse:BinarySecurityToken> Here is an example: <wsse:BinarySecurityToken att1="abc" att2="cd3" att3="adfa">This is the text I am trying to extract!!!</wsse ...

Which items have the capability to activate the key press event within the DOM?

I've been conducting some tests and it appears that only form elements and the window object are able to activate the keypress event. I've referred to the MDN documentation and the spec, but I couldn't find a definitive list of the valid ob ...

Ways to calculate the product of two numbers using AngularJS within an HTML document

I am currently experimenting with AngularJS to create a unit conversion tool. I have set up two dropdown menus with unit values and would like to calculate the product of the selected values from the dropdowns. I have created a jsfiddle with my code, and I ...

Learn how to update scope variables in Angular.io's mat-autocomplete using the [displayWith] function feature

I'm encountering a problem where I am unable to update locally declared variables in the component controller that triggers the mat-autocomplete. The issue is that these variables are confined within a specific scope, preventing me from making any mod ...

Express Router Setup Error: The Router.use() method is expecting a middleware function, but instead received an undefined value

First and foremost, I want to clarify that I am well aware of the plethora of questions posed on this platform with a similar title. I have already attempted the suggestions provided there, but unfortunately, they either did not work for me or were too sp ...

Exploring methods to identify visible elements within a div container using Angular 2

Seeking a solution to detect visible elements within a dynamically scrolled container that contains data of varying heights. Utilizing Angular 8 framework for development. html example: <div id="container" style="height: 300px; overflow-y: scroll"> ...

When I click the button, the page goes blank and keeps loading endlessly

http://jsfiddle.net/iansan5653/7EPjH/17/ <head> <script type='text/javascript' src='https://www.google.com/jsapi'></script> <script type="text/javascript"> function chart() { var pressure; ...

Ways to effectively incorporate Bootstrap into Lit?

Currently, I am in the process of converting a website from Polymer to Lit. I have made good progress with it, but I have encountered a roadblock when it comes to styling. In order to simplify development and focus on functionality, I have been following t ...

Utilizing jQuery for real-time operations

I am working with two input text fields and I am looking to utilize jQuery to perform an operation between them. Here are the input text fields: <p> <label>Title 1</label> <span class="field"> <input type="text" ...

I want the navigation bar to appear only upon scrolling, but when I refresh the page it is already visible, and then vanishes as I start scrolling

I'm working on a project where I want the navigation bar to only appear after scrolling a certain distance down the page. However, I've noticed that when I refresh the browser, the navigation bar appears immediately and then disappears once I sta ...

Create HTML div elements dynamically with JavaScript based on database information

Can javascript be used to create divs from database information? ...