The button is failing to accurately update the displayed output

I am currently working on a random quote generator, and I seem to have encountered an issue when the "New Quote" button is clicked. To keep things concise, I have simplified and downscaled the data for the quotes, colors, and animations variables. The problem arises as follows: with each click of the button, and a smaller dataset, there is a noticeable delay in response time, and sometimes the colors, quotes, and/or animations do not change as expected. This is evident through inconsistent animation behavior. Even though it is plausible for the new output to match the previous one due to the limited dataset, the animation should still trigger every time but that's not always the case. Without the loadQuotes() function and no window.onload = loadQuotes();, reloading the page by pressing F5 works just fine. However, once I introduce the code within the loadQuotes() function and utilize window.onload = loadQuotes(); at the end of the page for the initial output, issues begin to arise. I attempted moving all variables and the randomNum() function outside the loadQuotes() function (under the assumption they are global), yet this led to the button becoming unresponsive after the page initially loads. My concern lies in achieving the desired page loading behavior akin to pressing F5 using only the button.

function loadQuotes() {
  function randomNum(min, max) {
    return Math.floor(Math.random() * (max - min + 1)) + min;
  }

  var quotes = [
    ["This is quote number one.", "Person 1"],
    ["This is quote number two.", "Person 2"],
    ["This is quote number three.", "Person 3"],
    ["This is quote number four.", "Person 4"],
    ["This is quote number five.", "Person 5"]
  ]

  var colors = [
    ["#096986", "#F69679"],
    ["#000866", "#FFF799"],
    ["#7D3563", "#82CA9C"]
  ]

  var animations = ["animated bounce", "animated flash", "animated pulse"]

  var getQuotes = randomNum(0, quotes.length - 1);
  var getColors = randomNum(0, colors.length - 1);

  var newColor0 = colors[getColors][0];
  var newColor1 = colors[getColors][1];
  var newAnimation1 = animations[randomNum(0, animations.length - 1)]
  var newAnimation2 = animations[randomNum(0, animations.length - 1)]

  document.getElementById("quote").innerHTML = "<h1>" + quotes[getQuotes][0] + "</h1>";
  document.getElementById("author").innerHTML = "<h3>" + "--- " + quotes[getQuotes][1] + "</h3>";

  $(document).ready(function() {
    $(".side-panel").css("background-color", newColor0);
    $(".middle").css("background-color", newColor1);
    $("#quote").addClass(newAnimation1);
    $("#author").addClass(newAnimation2);
    $(".btn").on("click", function() {
      loadQuotes();
    });
  });
}

window.onload = loadQuotes();
h1 {
  text-align: center;
  font-size: 3.5em;
}
h3 {
  font-size: 1.5em;
}
/* div { border: 1px solid black; } */

.full-height {
  height: 100vh;
}
.side-panel {
  background-color: newColor0;
}
.middle {
  background-color: newColor1;
}
.quote-box {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 80%;
  height: 65%;
  border-radius: 7.5%;
  background-color: #FFFFFF;
}
.quote-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  width: 90%;
  height: 50%;
}
<!DOCTYPE html>

<html lang="en-us">

<head>
  <title>Random Quote Machine</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" />
  <link rel="stylesheet" href="style.css" />

  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>

<body>
  <div class="container-fluid">
    <div class="row">
      <div class="col-xs-1 side-panel full-height"></div>
      <div class="col-xs-10 middle full-height">
        <div class="quote-box">
          <div class="quote-text">
            <p id="quote"></p>
            <p id="author"></p>
            <button type="button" class="btn btn-lg pull-right">New Quote</button>
          </div>
        </div>
      </div>
      <div class="col-xs-1 side-panel full-height"></div>
    </div>
  </div>
</body>

</html>

Answer №1

The issue you were facing stemmed from the incorrect nesting of your functions.

After reorganizing and cleaning up the logic, everything should work smoothly now.

Here is your revised code placed in the appropriate sections.

https://jsfiddle.net/abc123de/

const quotes = [
  ["Quote one", "Author 1"],
  ["Quote two", "Author 2"],
  ["Quote three", "Author 3"],
  ["Quote four", "Author 4"],
  ["Quote five", "Author 5"]
];

const colors = [
  ["#ABCDEF", "#FEDCBA"],
  ["#012345", "#6789AB"],
  ["#CDEF01", "#234567"]
];

const animations = [
  "animate fadeIn",
  "animate fadeOut",
  "animate zoomIn"
];

let selectedQuote,
    selectedColors,
    primaryColor,
    secondaryColor,
    animation1,
    animation2;

function displayQuotes() {
  selectedQuote = getRandomNumber(0, quotes.length - 1);
  selectedColors = getRandomNumber(0, colors.length - 1);
  primaryColor = colors[selectedColors][0];
  secondaryColor = colors[selectedColors][1];
  animation1 = animations[getRandomNumber(0, animations.length - 1)];
  animation2 = animations[getRandomNumber(0, animations.length - 1)];

  document.getElementById("quote").innerHTML = `<h1>${quotes[selectedQuote][0]}</h1>`;
  document.getElementById("author").innerHTML = `<h3>--- ${quotes[selectedQuote][1]}</h3>`;

  $(".box1").css("background-color", primaryColor);
  $(".box2").css("background-color", secondaryColor);
  $("#quote").addClass(animation1);
  $("#author").addClass(animation2);
}

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

$(document).ready(function() {
  $("button").on("click", function() {
    displayQuotes();
  });

  displayQuotes();
});

Answer №2

The issue you're experiencing is due to calling the loadQuotes function within itself, creating a loop of clicks on click events. This caused my browser's RAM usage to spike up to 3GB after a few clicks, so it's important to resolve this issue

I've made some modifications that should help you out: https://jsfiddle.net/qv5he9z0/6/

Firstly, I moved the JavaScript code from the HTML file to the javascript panel.

All the code is now enclosed within:

$(document).ready(function () { });

Variables are now declared at the beginning for easy updating and changing values in different functions. They are now global.

I also swapped out (since we have jQuery):

document.getElementById("quote").innerHTML = "<h1>" + quotes[getQuotes][0] + "</h1>";

with

$("#quote").html("<h1>" + quotes[getQuotes][0] + "</h1>");

and

document.getElementById("author").innerHTML = "<h3>" + "--- " + quotes[getQuotes][1] + "</h3>";

with

$("#author").html("<h3>" + "--- " + quotes[getQuotes][1] + "</h3>");

I also moved the following code outside the loadQuotes function (to prevent loops of clicks on click events):

$(".btn").on("click", function() {
    loadQuotes();
});

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

loading a codeigniter page via AJAX calls

Currently, I am delving into the realm of AJAX using jQuery. To kick things off, I decided to utilize a code snippet from w3school, which performed admirably. Afterwards, I proceeded to incorporate the code into a view page within the Codeigniter framewor ...

Navigating with AngularJS to the Public page, such as the signup page

Having an issue with Angular.js (and possibly express) routing. I was able to resolve the routing for regular subpages, but now I need to include some publicly accessible pages like signup, password-lost/reset, and so on. However, whenever I try to access ...

I'm having trouble locating the source of the popstate loop that is generating numerous history entries

I am currently working on a project to create a dynamic webpage where the content of the main div gets replaced when certain navigation links are clicked. I have successfully implemented the pushstate function to update the div content and change the URL a ...

Configuring cloud code on Back4App to automatically trigger a POST API request to update the ESP

I am a beginner when it comes to developing APIs and cloud code, and I need help figuring out how to create an API that can add or update users in my back4app database table to my sendinblue (ESP) contact list. Could someone provide guidance on what shoul ...

Disappear solely upon clicking on the menu

Currently, I am working on implementing navigation for menu items. The functionality I want to achieve is that when a user hovers over a menu item, it extends, and when they move the mouse away, it retracts. I have been able to make the menu stay in the ex ...

`What purpose does the data-view attribute serve in Durandal JS?`

While experimenting with the Durandal JS starter kit application, I happened to view the page source in Mozilla browser and noticed the following. <div class="" data-view="views/shell" style="" data-active-view="true"> </div> I couldn't ...

StartsWith() function failing when used in conjunction with takeWhile()

I'm trying to iterate over an Immutable List and create a new list containing only the entries that start with a specific string. In this case, I want to find all states that begin with the letter 'D'. However, instead of returning a list wi ...

stopping the current menu selection from altering its color

How can I stop the color change when hovering over the selected menu item? Here's my code: <html> <head> <title> Another Page </title> <link rel="stylesheet" href="style4.css" type="text/css" /> & ...

Encountering an issue with WebRTC where the 'addIceCandidate' function on RTCPeerConnection is failing, resulting in an error displayed on the console. However, despite this error

I am facing an issue with connecting two peers using webRTC. While I can successfully display both local and remote videos, as soon as the remote video appears, the candidate object turns null and an error message is logged on the console. TypeError: Fail ...

Update the style of elements on each iteration in Symfony2

I have implemented a collapsible CSS page for FAQs. While static text works fine, I am fetching questions and answers from the database which is causing an issue. In its standard CSS version, the collapsible FAQ appears as follows: <div clas ...

Troubleshooting the Angular Fullstack + CORS issue: "XMLHttpRequest cannot load

I've been wracking my brain trying to figure this out. Utilizing the yeoman generator angular-fullstack, I created a simple Angular app on a NodeJS server with Express. The app makes remote service calls, so there are no API server side calls within ...

Firefox is having trouble loading SVG files

For some reason, the SVG image is loading on all browsers except for Firefox. I checked the DOM but couldn't find the code. Just to clarify, I am serving the page from Tomcat 9.0.34 <kendo-grid grid-options="gridOptions"> <img src= ...

Struggling to remove the excess white space while working with Bootstrap 5

Trying to eliminate the white space visible in the image. Utilizing Bootstrap for my project, but still getting acquainted with it. My teacher suggested (without reviewing any code) that a container might be causing the issue. I disagree as the HTML contai ...

What are the steps to fixing a CSS problem in order to show an image caption?

Looking to enhance image display by adding captions? Check out the CSS and HTML code provided below: <style type="text/css"> .caption-style-1{ list-style-type: none; margin: 0px; padding: 0px; } .caption-sty ...

Examining the process through which an element attains focus

Scenario I am working on a Backbone application that has an event listener set up for focus events on a textarea. Since Backbone relies on jQuery events, my main concern revolves around jQuery focus events. Inquiry Is there a method to determine how an e ...

In React hooks, you can easily deactivate an image element upon the first click on a toggle, and then reactivate it using setTimeout

I am currently working on a feature for parking slot allocation based on reservation time. The main goal is to allow users to click on an image element which will toggle to a second image and then disable the toggle functionality for a set period of time ( ...

Exploring the capabilities of ExcelJS for reading xlsx files within an Angular environment

I'm trying to access a source file, make some changes to it, and then provide it for the user to download. However, I am facing an issue with reading the source file from my project directory. Below is my implementation using excelJS for file reading: ...

Angular 2 Error: Unable to access the property 'value' as it is undefined

Whenever I click on the Submit button, this error pops up in the browser console. https://i.sstatic.net/57a5N.jpg In my application, I am attempting to retrieve information about the code uploaded by a Student. I am at a loss as to why this error is bein ...

Generating a compilation from an array in React JS

Having trouble creating an array to store my category links and display them on my website. However, I'm not seeing anything in my DOM. Any assistance would be greatly appreciated :) import React from "react"; import { SidebarCategory } from './ ...

Sorting high volumes of data in MongoDB

When using NodeJS, I encountered a strange issue. After renaming my telemName table and fetching fresh data, the code worked perfectly fine as always. However, the current collection has exceeded Total Results: 1649272. db.collection(telemName).find(optio ...