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

The Sequelize object is not defined in the current context, but it was referenced in the preceding "

When attempting to access an object, I am encountering an issue where it is returning as undefined, despite having created the object earlier in the statement and successfully accessing it from a separate then statement. Here is a breakdown of the logic b ...

What is the best way to create an answer label box that validates your response?

I am looking to design a question box label that resembles a search box. In this unique setup, users will have the option to input their answer into the question label. For example, if the user types 'kfuffle' as the answer, they will automatical ...

What is the best way to access all sections of a JSON file containing nested objects within objects?

Here is an example of my JSON file structure: [{ "articles": [ { "1": { "sections": [ {"1": "Lots of stuff here."} ] } }, { "2": { "sections": [ {"1": "And some more text right here"} ] } } }] The c ...

The width of the Div element is not following the specified dimensions, and it also has an unspecified margin

Check out my code snippet at: http://jsfiddle.net/8z4aw/ I'm trying to create a table-like layout using div elements, but for some reason the browser is not respecting the specified widths and seems to be adding an unwanted right margin. Where is thi ...

Tips for sending a form and showing results without the need to refresh the page

I am currently working on developing a basic calculator that takes a user input number and displays the calculated output without redirecting or reloading the page. However, since I have no experience with JavaScript (js) and Ajax, I am seeking assistance ...

Mobile devices are having issues with CSS rendering

I've encountered an issue with my CSS code. It seems to be working fine until the @max-width:767 media query, but then it stops working on the resolution immediately below it, which is @425. However, it starts working again on resolutions below that. ...

Inconsistencies in JavaScript comparison across various web browsers

Here is a snippet from my JavaScript code var dataList = eval(strArray[0]); for (i = 0; i < dataList.length; i++) { console.log(((dataList[i].isFollowed == 0) ? "Follow" : "Unfollow")); } However, this code exhibits varying behavio ...

Adjust the href link value when a new option is selected

I currently have a select element displayed below. Next to it, there is a link that sets the eID value to a session value. However, I want this value to be updated dynamically whenever a different eID value is selected from the dropdown. Although I can r ...

The array map is not displaying properly in the table

I am trying to map an array on my webpage and display the results in a table. However, I am facing an issue where the content is not showing up when I compile the page. Can someone please assist me with this problem? When I print the content of a variabl ...

Exploring the differences between setting routes in Express using app.use() and app.get()

I have a website stub with routing set in two different places. First, in app.js: ... var index = require('./routes/index'); var users = require('./routes/users'); ... app.use(express.static(path.join(__dirname, 'public'))); ...

Combining JSON data in Node.js with a custom structure is essential

Greetings! I'm currently working on a project that involves creating a JSON file using all the JSON files in a specific directory. My goal is to have this main JSON file automatically update whenever a new file is added to the directory. To achieve th ...

When implementing CSS object-fit: contain on an image, it may result in empty spaces surrounding the image

Within my image-wrapper container, I have an image with a variable resolution. The container itself has fixed dimensions for height and width. My goal is to center the image within the container both horizontally and vertically while adding a box-shadow e ...

The insertion was unsuccessful: Technique used in Meteor 1.3 and React

I am looking to add some simple text to the MongoDB using React. However, when I submit the form, the following error message is displayed in the console: insert failed: Method '/resolutions/insert' not found My setup includes autopublish and i ...

Getting the location of a mouse click and adding tags (marks) on an image: a simple guide

Is there a way to incorporate images with tagged marks similar to Facebook's image tagging feature? How can I retrieve the X and Y coordinates of tags on the image itself (not the screen) and display them in a responsive manner? ...

Struggling to perfectly align a Wufoo form within an iframe using CSS

I have integrated a web form from Wufoo into my webpage using an iframe. Custom CSS can be used to style the form and I am trying to center it within the iframe. Below is the HTML code of the form displayed in the iframe: <div id="container" class="lt ...

What is the best way to leverage local storage/memory to save information for my text-based RPG game?

Currently, I am in the process of creating a text-based RPG on Codecademy. However, I am facing a challenge when it comes to implementing a save/load system using JavaScript/HTML. My idea is to create a system where players can type "save" into a prompt, ...

What is the best way to align div elements in HTML5?

I've spent countless hours trying to properly display and align multiple divs. Despite extensive research, I just can't seem to get it right. What I'm aiming for is to have the title of a section in the top left corner, an info box to the l ...

When using `app.all(*)`, the entire HTML is returned even when making a POST request

Utilizing app.all(*) within my express route to direct to the pagenotfound.html page. Therefore, at the conclusion of all routes, I include: app.all('*',security.isLoggedIn, (req, res, next) => { res.render("pageNotFound.ejs") }) ...

Encounters an undefined error when attempting to access a non-existent value within a nested object in Vue.js

I am currently facing an issue with accessing a nested object property. Here is the scenario: const data={a:'value1',b:{c:'null'}} When trying to access the 'c' property within object 'b', I am encountering a proble ...

Efficiently handling multiple form submissions using a single jQuery Ajax request

I'm working on a page that has 3-4 forms within divs, and I want to submit them all with just one script. Additionally, I want to refresh the content of the specific div where the form is located. However, I'm unsure of how to specify the current ...