What is the best way to retrieve information from a JSON file and navigate through content with previous and next buttons using jQuery?

A functionality is being developed using jQuery to showcase content from a JSON file whenever the user interacts with the navigation links (prev and next arrows). Upon landing on the page, the initial JSON object is displayed automatically. Subsequent clicks on the "Next" arrow reveal the subsequent objects from the JSON file. Once clicked four times, the display resets back to the first JSON object. Regardless of the JSON file's size, only four objects are visible to the user.

At present, the JavaScript code on the page, which was inherited, contains hardcoded divs for each of the four views. The objective is to configure the system in a way that all data is sourced externally from a JSON file. The current script utilizes jQuery successfully to retrieve the JSON file. For consistency across the updated version of the page, continuing to use jQuery is preferred.

Within the existing jQuery setup, there is a loadData() function that was utilized for testing the connection to the JSON file. Following successful testing, the loadData button has been removed. Once the method to cycle through the initial four JSON objects is determined, the HTML and CSS components can be finalized.

We appreciate any insights or suggestions provided regarding this matter.

  
  <!— Code Snippet —>

Answer №1

From your query, it appears that you are currently facing a challenge with

I just need to figure out how to loop through the initial four objects in the JSON file so I can finalize the HTML and CSS.

Given the complexity of your example, here is a simplified version demonstrating how you can cycle through cards:

The variable issuesToLoopOn at the beginning allows you to specify the number of issues you want to iterate over, regardless of the length of the issues array.

View Example: https://jsfiddle.net/shaunakv1/4k2ufmvn/125/

HTML

<button id="previous">previous</button>
<button id="next"gt;next</button>

<div id="card">
  <div id="issue_number"></div>
  <div id="issue_label"></div>
  <div id="issue_link"></div>
  <div id="issue_link_cta"></div>
  <div id="display_description"></div>
  <div id="featured_image"></div>
  <div id="publish_date"></div>
  <div id="time_to_read"></div>  
</div>

JS

let issues;
const issuesToLoopOn = 3;

$(document).ready(async function () {
    const res = await fetch('https://raw.githubusercontent.com/loganatsea/features/main/issues');

    const json = await res.json();
    issues = Object.values(json.issues);

    //display first issue by default
    displayJson(issues[0]);
    //write current displayed index to dom ( optionally you can save in a state variable)
    $("#card").data('idx', 0)
    $("#card").data('total', issues.length);
});

$("#next").on('click', () => updateNextCard(1))
$("#previous").on('click', () => updateNextCard(-1))


function updateNextCard(by) {
    let currentIdx = parseInt($("#card").data('idx'));
    let nextIdx = currentIdx + by;

    if (nextIdx === issuesToLoopOn) nextIdx = 0;
    else if (nextIdx < 0) nextIdx = issuesToLoopOn - 1;

    console.log(nextIdx); //update dom and state

    displayJson(issues[nextIdx]);
    $("#card").data('idx', nextIdx);
}

function displayJson(obj) {
    Object.keys(obj).forEach(key => {
        $(`#${key}`).html(`<p><b> ${key} </b>: ${obj[key]} </p>`);
    });
}

Update I have updated the answer to show how to use values from JSON and display them on the DOM. There's no need to "parse" JSON in JavaScript. You can simply treat it as an Object or Array. JSON stands for JavaScript Object Notation. In your situation, you can place the div elements wherever in the HTML as long as they have the correct ID referenced by jQuery selector for it to work.

Here's the revised fiddle:

https://jsfiddle.net/shaunakv1/4k2ufmvn/157/

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

Empty array is logged by the server after sending a JavaScript variable through post request

When I use console.log(request.body), the terminal displays {} instead of logging the variable ownerSteamId. Here is my code: Server-side JavaScript: const express = require('express'); const app = express(); const bodyParser = require('bod ...

How to make background color transparent in CSS for Safari browser

Does anyone know how to make the background color transparent in Safari? Right now, my PNG file is showing with a white background instead of being transparent. I have attempted: background-color: transparent; background-color: rgba(255,255,255,0); appe ...

What is the reason behind Firefox failing to display a linear gradient when the background-size values are more than 255px?

I am working on creating a grid overlay using an absolutely positioned non-interactive div. My approach involves using the repeating-linear-gradient property as suggested by others for this purpose. The functionality works smoothly in Chrome, but I seem to ...

Tips for creating an easyui layout using multiple nested layouts

I have integrated easyui nested layout into my application. I followed the code snippet provided in the easyui demo. <div class="easyui-layout" style="width:700px;height:350px;"> <div data-options="region:'north'" style="height: ...

.bootstrapMaterialDatePicker does not work within Codeigniter version 3

I am experiencing an issue with my form that has two date fields stored as varchar <div class="row clearfix"> <div class="col-lg-2 col-md-2 col-sm-4 col-xs-5 form-control-label"> <label for="ar ...

How can I use jQuery to switch classes or activate a click event on the most recently clicked element?

Within my <ul></ul>, there are 4 <li> elements. <ul class="wcarchive-terms-list"> <li class="wcarchive-term wcarchive-term-parent woof_term_224"> <label class="wcarchive-term-label"> <span cla ...

Incorporating middleware to handle 404 errors in Express

scenario app.use("/api/tobaccos", tobaccos); app.use(function(err, req, res, next) { console.error(err.message); }); API details: router.get("/:id", async (req, res) => { console.log("GET TOBACCO:" + req.params.id); ...

Permanently remove the span tag and any associated text from the HTML document

Currently, I am working on a project that involves numerous page numbers marked using the span class. Below is an example of this markup: <p>Cillacepro di to tem endelias eaquunto maximint eostrum eos dolorit et laboria estiati buscia ditiatiis il ...

Adjust the field's color depending on the outcome displayed within

I'm trying to implement a feature where the field value changes to green when "OK" is selected and red when "NOK" is chosen. I have written the following JavaScript code but it's not working as expected - the colors change before clicking submit, ...

Unable to choose multiple options within a selection field

My webgui testing involves the use of selenium, which includes the following method: protected static selectListItems(String id, String value1, String value2, String value3,String value4){ String values = "" if(StringUtils.isNotBlank(value1)) ...

Unable to cancel the setTimeout function by using clearTimeout as the value appears to be null for unknown reasons

Within my react-native application, I am attempting to halt the execution of a setTimeout function by utilizing clearTimeout. The instance of setTimeout is stored in a global variable. let timeoutId: any = null; const doOtp = () => { if(can ...

The placeholder text feature for Google custom search is ineffective when using the Edge browser

After adding the following code to the end of the Google custom search script, I encountered an issue: window.onload = function(){ document.getElementById('gsc-i-id1').placeholder = 'Search'; }; Although this code successfully added ...

Visualizing CSV data with charts and tables

Can you provide guidance on effectively presenting a large volume of CSV data? We aim to showcase multiple counts, averages, and other statistics. Are there any specific tools or techniques that can assist with this task? ...

Executing a PHP file in JavaScript without using the jQuery library can be achieved by making

As a beginner in php and javascript, I am seeking a straightforward method to execute a php file from javascript. While browsing through various examples (here and here), most of them rely on jQuery which I prefer to avoid. My goal is to trigger the updat ...

React Native - useEffect causing a double render on Home screen

I am facing an issue where my functional component "Home" keeps rendering again after I receive data from a function in the "useEffect" hook. If I use the "set" statement to store the data from the function in a const, it triggers a re-render of the Home c ...

The error message "TypeError: window.Razorpay is not a constructor" indicates that

I am attempting to integrate RazorPay into my React app, but I am encountering the following error: https://i.stack.imgur.com/iFvdz.png Here is the code snippet: import TshirtImg from "./tshirt.jpg"; // import Razorpay from 'razorpay' ...

Jest test encounters an error due to an unexpected token, looking for a semicolon

I've been working on a Node project that utilizes Typescript and Jest. Here's the current project structure I have: https://i.stack.imgur.com/TFgdQ.png Along with this tsconfig.json file "compilerOptions": { "target": "ES2017", "modu ...

Is there a way to retrieve object data without using the map JS function?

Currently, I am delving into a project involving React, Redux, and JS. The tutorial I am following incorporates a dummy object within the redux store as illustrated below. const initState = { posts:[ [ {id: '1', title: 'Fi ...

Trouble in testing: ComponentDidMount is mysteriously bypassed by Jest/Enzyme when it's supposed to be triggered

In my code, there is a method called componentDidMount that triggers the fetchUser() function. I am currently working on testing the componentDidMount method. Here is the Component Code: static propTypes = { match: PropTypes.shape({ isExact: Pr ...

Omitting "a" elements with a designated ancestor from a jQuery scroll operation

I successfully added smooth scrolling to my webpage using the provided script. However, I also have a section with tabs where I do not want the smooth scrolling effect. Here is my jQuery code: $('a[href*="#"]') // Remove links that don&apos ...