Book Roulette: Your Next Random Read

I created a code for a random quote generator and now I want to create something similar, but with images this time. I am looking to add a feature on my page where it can recommend a book by displaying its cover image when a button is clicked.

For the previous quote generator, I used the following code:

HTML:

<div class="quotes">
                <h1 class="quote-generator">Simple Quote Generator</h1>
                <div id="quoteDisplay"></div>
                <button onclick="newQuote()" class="button-quote">New Quote</button>
                <script src="./js/quotes.js"></script>
            </div>

JavaScript

var quotes = [
    'One must always be careful of books,<br>and what is inside them,<br>for words have the power to change us.<br>—Cassandra Clare',
    'Only the very weak-minded refuse to be<br>influenced by literature and poetry.<br>—Cassandra Clare',
    // more quotes here
] 
function newQuote() {
    var randomNumber = Math.floor(Math.random() * (quotes.length));
document.getElementById('quoteDisplay').innerHTML = quotes[randomNumber];
}

Now, I am wondering how I can modify the quotes in the variable "quotes" to display as images instead?

Answer №1

Here is a way to achieve this functionality with some enhancements that prevent the same book from being offered twice.

If you have any questions, feel free to ask.

var images = [
  'https://m.media-amazon.com/images/I/81jRqrKKObL._AC_UL800_FMwebp_QL65_.jpg',
  'https://m.media-amazon.com/images/I/81JgX8VgZiL._AC_UL800_FMwebp_QL65_.jpg',
  'https://m.media-amazon.com/images/I/71CBWHK035L._AC_UL800_FMwebp_QL65_.jpg',
  'https://m.media-amazon.com/images/I/91pXKpUfGgL._AC_UL800_FMwebp_QL65_.jpg',
];

let lastBook = -1; // Ensure no repeated books are offered

function newBook() {
    let randomNumber;
    do {
      randomNumber = Math.floor(Math.random() * (images.length));
    } while (randomNumber === lastBook);
    lastBook = randomNumber;
    document.getElementById('bookCover').src = images[randomNumber];
}
<div class="quotes">
  <h1 class="quote-generator">Simple Book Generator</h1>
  <div id="quoteDisplay">
    <img id="bookCover" style='width: 100px' src=''>
  </div>
  <button onclick="newBook()" class="button-quote">New Book</button>
  <script src="./js/quotes.js"></script>
</div>

Answer №2

Transform your array into an Array of Objects to easily store images within each object. Let me know if this method is effective for you.

<div class="quotes">
    <h1 class="quote-generator">Simple Quote Generator</h1>
    <div >
        <img src=""/>
        <p id="quoteDisplay"></p>
    </div>
    <button onclick="newQuote()" class="button-quote">New Quote</button>        
</div>


    
    let quotes = [
                    {
                        data: `Only the very weak-minded refuse to be<br>influenced by literature and poetry.<br>—Cassandra Clare`,
                        img: '1.jpg'
                    },
                    {data:`I am not afraid of storms,<br>for I am learning how to sail my ship.<br>—Louisa May Alcott`,
                        img: '2.jpg'
                    },
                    {data:`Nice things don\'t happen in storybooks.<br>Or when they do happen, something bad happens next.<br>Because otherwise the story would be boring, and no one would read it.<br>—Holly Black`,
                        img: '3.jpg'
                    {data:`You don\’t forget the face of the person who was your last hope.<br>—Suzanne Collins`,
                        img: '4.jpg'
                    {data:`You look best when you\'re you.<br>—Lynn Painter`,
                        img: '5.jpg'
                    {data:`“Everything\’s a game, Avery Grambs.<br>The only thing we get to decide in this life<br>is if we play to win.<br>—Jennifer Lynn Barnes`,
                       img: '6.jpg'
                    {data: `“Why do I have to tell a story?” I asked.<br>“Because if you don\’t tell the story,<br>someone else will tell it for you.”<br>—Jennifer Lynn Barnes`,
                        img: '7.jpg'
                    {data: `I mean, there\’s a reason all books end right after the couple gets together.<br>No one wants to keep reading long enough to see the happily ever after turn into an unhappily ever after. Right?<br>—Alex Light`,
                        img: '8.jpg'
                    {data: `Break my heart,<br>break it a thousand times,<br>it was only ever yours to break anyway.<br>—Kiera Cass`,
                        img: '9.jpg'
                    }
];


    function newQuote(){
        let randomNumber =  Math.floor(Math.random()*9);
        const target = document.getElementById('quoteDisplay');
        target.innerHTML = quotes[randomNumber].data;
        document.getElementsByTagName('img')[0].src= quotes[randomNumber].img;
    }

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

Minor Chrome compatibility problems with CSS alignment

As someone who is new to stackoverflow, I've always found it to be a valuable resource for answers. I've had success building HTML 5 banner ads using GSAP (Greensock Animation Platform) in the past, but now I'm facing a CSS alignment issue t ...

Automatically switch to dark mode at specified times: A simple guide

Here is the current method for toggling themes: let themeToggler = document.getElementById('theme-toggler'); themeToggler.onclick = () => { themeToggler.classList.toggle('fa-sun'); if (themeToggler.classList.contains('f ...

Instructions for activating and deactivating a numerical input field with a checkbox

Is there a way to create a pair of a checkbox and number field that are linked together? When the checkbox is clicked, it should disable the associated number field. Javascript File: $(document).ready(function(){ $("input[name=check]").click(function(){ ...

What is the best way to execute a sequence of consecutive actions in a protractor test?

To achieve logging in, verifying, and logging out with multiple users, I decided to use a loop. I came across a helpful post that suggested forcing synchronous execution. You can find it here. Below are the scripts I implemented: it('instructor se ...

Adding to the beginning of a list in JQuery mobile

Having trouble figuring out how to prepend my list in jQuery mobile while keeping the divider on top of the most recent item added. I attempted to prepend the newly added item, but it ended up shifting the divider to the bottom instead. function loadScan ...

Stylish border radius for Bootstrap progress bars

Here is a snippet of code that I am struggling with: .progress-bar{ border-top-right-radius: 40px !important; border-bottom-right-radius: 40px !important; -webkit-box-shadow: none !important; -moz-box-shadow: none !important; box-sha ...

Interactive image grid with adjustable description field per image upon selection

My goal is to create a grid of images with a single text field below the grid. This text field should display the description of the image that was last clicked. The grid is implemented using floating divs within a main div, as shown in the code snippet be ...

You should be providing a string value as expected. It seems that you may have overlooked exporting your component from the correct file it was defined in, or perhaps there is confusion with default and named

I encountered a strange error despite meticulously organizing and exporting/importing files. The code is structured from components to the App render method. Item.js import React from 'react'; import './Global.css' const Item = ({data ...

Nuxt.js is throwing a TypeError because it is unable to access the 'minify' property since it is undefined

When I try to generate a Nuxt app using "npm run generate" or "npm run build", I encounter an issue where it throws a TypeError: Cannot read property 'minify' of undefined. Does anyone know how to solve this? TypeError: Cannot read property &apo ...

Should I avoid declaring global app variables in Angular?

After browsing several examples online, I have come across a common pattern in AngularJS code. The basic structure involves creating a new module using the angular.module() method and then retrieving it in other files within the same module. var app = ang ...

A solution for accessing computed properties within a v-for loop

Currently, I am facing a challenge with the code provided below. It seems that computed properties do not support parameters. Do you happen to have any suggestions on how to overcome this issue? I am considering using watchers on functions but I am also ...

Customize Bootstrap 4 borders within a row

I am currently facing an issue with my code, where there is a border at the bottom of every row. Click here to view the code Unfortunately, I have noticed that the border at the bottom of each row does not extend across the full width. This occurs even wh ...

What is the best way to properly redirect a page using a router link in Vue.js 2?

I've encountered an issue with the router-link component in Vue.js 2. I have set up my router file index.js import Vue from 'vue'; import VueRouter from 'vue-router'; import HomeView from '../views/HomeView.vue'; import ...

Combining two input text strings

A React component I'm working on takes the user's first and last name to create unique usernames for them. class App extends Component { render() { return ( <div className="App"> First name:<br/> <input ...

The collapsible menu does not toggle when I tap on the icon

I am currently troubleshooting an issue with this link "https://sampledemos.online/training/index.html" where the toggle feature is not functioning properly. Below are the codes I have written: <aside id="layout-menu" class="layout-menu m ...

Retrieve user input from an HTML form and pass it as a parameter in a jQuery AJAX request

Is there a way to pass a value from a user input in an HTML file to jQuery.ajax? Take a look at the code snippet from my JS file: jQuery(document).ready(function() { jQuery.ajax({ type: 'POST', url: 'myurl.asp ...

Unable to refresh the fullcalendar section following an ajax post click

Currently developing a calendar using fullcalendar. I have created an ajax button that retrieves events from another php page. The first click on the ajax button works fine, displaying a nice month calendar with events. However, my issue arises when I cl ...

Is it necessary to implement clustering for each route in an Express.js application?

Currently, I am utilizing the cluster module to fork my application within my index.js, which serves as the primary file in the root directory of my website. My application consists of numerous routes. Should I incorporate the cluster code to encapsulate a ...

How can you utilize positioning and margins with Flexboxes?

<template> <div class="flex justify-center"> <div class="h-px-500 md:w-1/6 bg-orange-200 text-center">1</div> <div class="h-px-500 md:w-1/6 bg-orange-300 text-center">2</div> <div class="h-px-500 md:w-1/ ...

What is the best way to create a mobile design in Dreamweaver while utilizing the same css file as my Desktop code?

Where does my layout provide a solution, and what adjustments can be made? I attempted modifying the screen dimensions in the Dw Design page without success. ...