Is there a way to showcase my information on flash cards using JavaScript?

Currently, I am developing a full stack application that utilizes JavaScript on both the front and back end. This application allows users to create their own flashcards set. Upon clicking "View Cards," the data is fetched and the question-answer pair is displayed on each side of the card. The app is designed to show one card at a time, with options for scrolling through other cards using the "Previous" or "Next" buttons. While I have successfully fetched and converted the data to JSON, as well as displayed at least one item from the database properly, I am facing issues when attempting to scroll through the cards. Sometimes the browser returns an error, and certain cards do not render both sides correctly. How can these problems be addressed?

const flashCard = document.querySelector(".flashcard");
const flipBtn = document.querySelector(".flip-btn");
const prevBtn = document.querySelector(".prev-btn");
const nextBtn = document.querySelector(".next-btn");
let frontOfCard = document.querySelector(".front-content");
let backOfCard = document.querySelector(".back-content");

const displayCards = () => {
  getCardInfo()
  flipBtn.innerHTML = "Flip"
  flipBtn.removeEventListener("click", displayCards)
}

flipBtn.addEventListener("click", displayCards)

const flash = () => {
  if (flashCard.style.transform != "rotateX(180deg)") {
    flashCard.style.transform = "rotateX(180deg)"
  } else {
    flashCard.style.transform = "none"
  }
}

const getCardInfo = async () => {
  const itemBody = {
    method: "PUT",
    headers: {
      Accept: "application/json",
      "Content-Type": "application/json" 
    }
  }

  const data = await fetch(window.location.href, itemBody)
  const jsonData = await data.json()
  console.log(jsonData)

  let idx = 0;
  frontOfCard.innerHTML = jsonData[idx].Answer
  backOfCard.innerHTML = jsonData[idx].Question

  flashCard.style.display = "block";

  flipBtn.addEventListener("click", flash);

  scrollThroughCards(idx, jsonData);
}

function scrollThroughCards(idx, data) {
  prevBtn.addEventListener("click", (e) => {
    flashCard.style.display = "none"

    setTimeout(() => {
      frontOfCard.innerHTML = data[idx--].Answer
      backOfCard.innerHTML = data[idx--].Question
      flashCard.style.display = "block"
    }, 1000)

    e.preventDefault()
  })

  nextBtn.addEventListener("click", (e) => {
    flashCard.style.display = "none"

    setTimeout(() => {
      frontOfCard.innerHTML = data[idx++].Answer
      backOfCard.innerHTML = data[idx++].Question
      flashCard.style.display = "block"
    }, 1000)

    e.preventDefault()
  })

}

app.get("/card/:id", checkAuthenticated, async (req,res) => {
  const { id } = req.params

  const data = await Card.findAll({ where: { NoteId: id } });


  res.render("cards-page", { 
    noteid: id,
    Cards: data
  })
});

app.put("/card/:id", checkAuthenticated, async (req,res) => {
  const { id } = req.params

  const data = await Card.findAll({ where: { NoteId: id } });

  res.json(data)
})


app.post("/card/:id", checkAuthenticated, async (req, res) => {
    const { Question, Answer, NoteId } = req.body;
    const newCard = await Card.create({
        Question,
        Answer,
    NoteId
    });

  res.redirect(`/card/${NoteId}`)
});

Answer №1

The scrollThroughCards function had a flaw in which it did not include boundary checks and improperly utilized increment and decrement operators.

function scrollThroughCards(idx, data) {
  prevBtn.addEventListener("click", (e) => {
    // Check if there are cards to the left of index 0
    // If not, exit the function early
    if (idx <= 0) return;

    flashCard.style.display = "none"

    setTimeout(() => {
      idx--; // Decrease the index first
      // Use the modified index
      frontOfCard.innerHTML = data[idx].Answer
      backOfCard.innerHTML = data[idx].Question
      flashCard.style.display = "block"
    }, 1000)

    e.preventDefault()
  })

  nextBtn.addEventListener("click", (e) => {
    // Check if there are more cards beyond the end of the list
    // If not, exit the function early
    if (idx >= data.length - 1) return;

    flashCard.style.display = "none"

    setTimeout(() => {
      idx++; // Increase the index first
      // Use the modified index next
      frontOfCard.innerHTML = data[idx].Answer
      backOfCard.innerHTML = data[idx].Question
      flashCard.style.display = "block"
    }, 1000)

    e.preventDefault()
  })
}

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

Issues with checkboxes in HTML 5 showing inconsistent behavior

Utilizing: APS.NET MVC 4.0 Incorporating javascript/jquery to manage check boxes within a table, I have encountered an issue where the code functions correctly during the first and second passes. Initially, it checks all the checkboxes, while on the secon ...

Incorporating and designing a side button using jQuery Mobile

I'm working on adding a button to the left side of the screen that is round (but not necessarily) and partially visible, with a visually appealing design. This button will allow users to open a side menu panel. Below is the HTML code for the button: ...

Obtaining the width of a child table using Jquery

I have a question that might seem simple, but I can't figure it out. How can I use jQuery to get the width of a table that is a child of a div with the class "test"? <div class="test"> <div id="one"> </div> <table> <thead&g ...

A mistake has been identified: The object could potentially be 'null'. TS2531 for window.document

This is my first time integrating TypeScript into my project. When attempting to access something using window.document.getElementById(), I keep encountering the error: Type error: Object is possibly 'null'. TS2531 I've looked online for ...

Utilizing AngularJS: Establishing a Universal Parent State in UI-Router for Modals and Shared Components

In my code using UI-Router and Bootstrap-ui modal, I have defined the state as shown below. reference var state = { name: 'modala', parent: 'home', onEnter: function($modal, $state) { modalInstance = $modal.open({ ...

Having trouble modifying a nested object array within a treeview component in Reactjs

Thanks for your help in advance! Question: I'm having trouble updating a nested object of an array in a treeview using Reactjs. Please refer to the code and sandbox link below: https://codesandbox.io/s/cocky-leakey-ptjt50?file=/src/Family.js Data O ...

Guide on navigating the mouse pointer to an element using Selenium and nodejs

Currently, I am developing with nodejs and have incorporated the selenium module. However, I am facing an issue where I need to click on a button by moving the mouse pointer to the element location. Can someone please advise me on how to use ActionSequence ...

Instantiate a fresh Date object in JavaScript by passing in my specific parameter

Check out this code snippet: $(function () { var timestamp = 1443563590; //Tue, 29 Sep 2015 21:53:10 GMT var today2 = moment.unix(timestamp).tz('America/New_York').toString(); alert(today2); //var dateinNewYork = new Date(wh ...

At what point is ng-if triggered?

I am currently in the process of developing functionality for buttons that open directives in modal windows. To keep things simple, I decided to use a modal container flagged with the versus directive: <div ng-if="vm.Modal.Modal1"> <directive-for ...

Issue: Reactjs - Material-UI HTML Tooltip does not display dynamic HTML content.In the Reactjs

I have been using a customized HTML MUI Tooltip. Currently, it is functioning with static content but I am looking to make it dynamic. Unfortunately, it is not working with dynamic HTML content. Here is my attempted approach: const ADJUSTMENT_HELP_TEXT = ...

The issue of not being able to type in the sweetalert 2 input within a material UI modal in a

Within a card displaying an order, there is a sweetalert2 popup that opens when trying to cancel the order, asking for a cancellation reason. This feature works seamlessly on the orders screen. <Grid item md={8} sm={12}> orders.map((order) => ...

Erroneous Marker Placement Detected

Here is the data from my DataTable: Country Types of sales Total sales($) Name State United states of America chemicals 12662871 Obama GA Unite ...

Adjust the size of the external JavaScript code

Is it possible to adjust the size of the div element created by the external javascript code below? I've tried wrapping it in a div and setting the width, but the resizing doesn't seem to work. <div width = "100"><script type="text/jav ...

Incorporating an NPM module with dependencies within the Meteor framework

I'm encountering some difficulties while attempting to integrate an NPM package into my meteor project. The specific module I am trying to utilize is the steam package. In order to make this work, I have included the meteorhacks:npm package for mete ...

Is it possible to run React and Express on a single server?

I am currently in the process of developing a React website that includes a contact page. Within this contact page, users can input a message that will be directed to a specific email address. At the moment, my focus is on integrating Express with my Reac ...

The error handler function is missing in Zepto's $.post method

When I was using Zepto instead of jQuery, I noticed that while the $.ajax method has an error handler, other methods like $.post and $.get do not. Do you know why this is the case? Function Signature $.post(url, [data], function(data, status, xhr){ ... }, ...

Using Angular to convert JSON data to PDF format and send it to the printer

Currently, I am retrieving JSON data from an API and now need to convert this data into a PDF format for printing. I am encountering an issue where the CSS styling for page breaks is not rendering properly within my Angular component. When I test the same ...

Can JavaScript functions be automated on a web browser using Power BI tables?

I am facing a challenge with saving data from a powerbi table on a daily basis. When I hover over the table and click on the ellipsis menu, a button element is generated in HTML that allows me to save the data to a CSV file using Selenium. However, achiev ...

Eliminating empty elements from arrays that are nested inside other arrays

I am facing a challenge with the array structure below: const obj = [ { "description": "PCS ", "children": [ null, { "name": "Son", ...

Can CKEditor be integrated with Mutation Observer? If so, how can this be achieved?

Trying to detect changes in the current CKEditor content. The goal is to identify which element's content has been modified when a user writes multiple paragraphs. Not well-versed in JavaScript or jQuery, but managed to come up with this code after s ...