Making AJAX requests to retrieve data from a JSON database array, then utilizing the CSS visibility property to conceal HTML elements dynamically

As a enthusiastic beginner, I'm facing a challenge that seems to have no easy solution. Can someone please assist me with this:

How can I assign all the ids from a JSON database to the variable dotContainer, in order to hide all corresponding HTML id elements using the CSS property “dot-hide” (instead of manually specifying each id like "n788" with getElementById).

Essentially, I want the JSON database, which updates dynamically with new id values like n790 or n786, to asynchronously hide the matching dots on my HTML page using the “dot-hide” CSS class.

Here's the JavaScript code:

var dotContainer = document.getElementById("n788"); //THIS TO CONTAIN ALL ID VALUES FROM THE JSON DB
    var dataRequest = new XMLHttpRequest();
    dataRequest.open('get', 'https://raw.githubusercontent.com/sicronerver/sicronerve/master/dbn.json');
    dataRequest.onload = function() {
        var ourData = JSON.parse(dataRequest.responseText);
        //setInterval(function(){ 
            renderdata(ourData);
        //}, 1000);      
    };
dataRequest.send(); {
    }
function renderdata(dataobjectarray) {
        var texString = ""
        for (i = 0; i < dataobjectarray.length; i++) {
            texString += dataobjectarray[i].id + ",";
        }
  dotContainer.insertAdjacentText('afterEnd', texString); //REFERENCE OF JSON ID VALUES TO HIDE HTML ID ELEMENTS
  dotContainer.classList.add("dot-hide");
}

Here's the JSON data:

[{"id":"n787"},{"id":"n788"},{"id":"n789"}]

Here's the HTML structure:

<div class="grid">
  <a id = "n786" class = "dot" href="#786"></a>  
  <a id = "n787" class = "dot" href="#787"></a>  
  <a id = "n788" class = "dot" href="#788"></a>  
  <a id = "n789" class = "dot" href="#789"></a>
  <a id = "n790" class = "dot" href="#790"></a>

Here's the CSS styling:

.dot-hide {
  visibility: hidden;
  opacity: 0;
  transform: scale(.75);
}

.grid {
  display: grid;
  grid-template-columns: repeat(16, 1fr);
  grid-template-rows: repeat(9, 1fr);
}

.dot {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #777777;
}

.dot:hover {
  background-color: rgb(60, 255, 0);
  opacity: 50%;
}

.dot:active {
  background-color: #ff0000;
  opacity: 50%;
}

#n786 {
  position: relative;
  grid-column: 3 / span 2;
  grid-row: 6 / span 2;
}

#n787 {
  position: relative;
  grid-column: 6 / span 2;
  grid-row: 6 / span 2;
}

#n788 {
  position: relative;
  grid-column: 9 / span 2;
  grid-row: 6 / span 2;
}

#n789 {
  position: relative;
  grid-column: 12 / span 2;
  grid-row: 6 / span 2;
}

#n790 {
  position: relative;
  grid-column: 15 / span 2;
  grid-row: 6 / span 2;
}

If you want to see it in action, check out my CodePen: https://codepen.io/andijonson/pen/gOpEmEQ

Thank you for your help, Andi

Answer №1

To manipulate the CSS, you need to add and remove certain styles.

Here is a sample code snippet:

var dotContainer = document.getElementById("n788"); 
var dataRequest = new XMLHttpRequest();
dataRequest.open(
  "get",
  "https://raw.githubusercontent.com/sicronerver/sicronerve/master/dbn.json"
);
dataRequest.onload = function() {
  var ourData = JSON.parse(dataRequest.responseText);
  renderdata(ourData);
};
dataRequest.send();

function renderdata(dataobjectarray) {
  document.querySelectorAll("div a").forEach(x => {
    x.className = "dot";
  });
  var texString = "";
  for (i = 0; i < dataobjectarray.length; i++) {
    texString += dataobjectarray[i].id + ",";
  }
  dotContainer.insertAdjacentText("afterEnd", texString);
}

Check out the demo below:

window.onload = () => {
  function fetchData() {
    fetch(
      "https://raw.githubusercontent.com/sicronerver/sicronerve/master/dbn.json"
    )
      .then(res => res.json())
      .then(renderdata);
  }
  function renderdata(data) {
    document.querySelectorAll("div a").forEach(x => {
      x.classList.remove("hide");
    });
    data.forEach(item => {
      const elm = document.getElementById(item.id);
      elm.classList.add("hide");
    });
  }
  function start() {
    setInterval(fetchData, 2000);
  }
  start();
};
.hide {
  visibility: hidden;
  opacity: 0;
}

.grid {
  display: grid;
  grid-template-columns: repeat(16, 1fr);
  grid-template-rows: repeat(9, 1fr);
}

.dot {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background-color: #777777;
}
  
.dot:hover {
  background-color: rgb(60, 255, 0);
  opacity: 50%;
}
  
.dot:active {
  background-color: #ff0000;
  opacity: 50%;
}

#n786 {
  position: relative;
  grid-column: 3 / span 2;
  grid-row: 6 / span 2;
}

#n787 {
  position: relative;
  grid-column: 6 / span 2;
  grid-row: 6 / span 2;
}

#n788 {
  position: relative;
  grid-column: 9 / span 2;
  grid-row: 6 / span 2;
}

#n789 {
  position: relative;
  grid-column: 12 / span 2;
  grid-row: 6 / span 2;
}

#n790 {
  position: relative;
  grid-column: 15 / span 2;
  grid-row: 6 / span 2;
}
<div class="grid">
    <a id="n786" class="dot" href="#"></a>
    <a id="n787" class="dot" href="#"></a>
    <a id="n788" class="dot" href="#"></a>
    <a id="n789" class="dot" href="#"></a>
    <a id="n790" class="dot" href="#"></a>
</div>

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

Implementing method overrides in TypeScript class objects inherited from JavaScript function-based classes

I am facing a challenge with overriding an object method defined in a JavaScript (ES5) function-based class: var JSClass = function() { this.start = function() { console.log('JSClass.start()'); } } When I call the start() method, it pri ...

Fill a .js script with moustache.js

I need help with organizing some JavaScript code that needs to access server-side data. I want to keep this code in a separate .js file, but I'm having issues populating it with the necessary server information using moustache. Here is my current setu ...

Send a POST request with an NSDictionary set in the HTTPBody

I need to make a web service call using the POST method. I have to send a dictionary along with a URL to my web service. Below are the parameters required for my web service: ConversationMessage { authorUserId (string, optional), subject (st ...

Discover the Phillips Hue Bridge within the operational web application on a separate network

Utilizing the node-hue-api package on a Node.js/Express server to interact with the Hue API, I've developed an admin section of a website exclusively accessible to me for controlling my Hue lights. The functionality works seamlessly in my local develo ...

What steps can be taken to safeguard data while navigating within the Angular framework?

I am facing an issue with storing an array of items in a service (referred to as cart service) and displaying it in the component (cart.component.ts). The components bgview.component.ts and single.component.ts are involved in selecting individual items, wi ...

What is the process for initializing the default/prefilled value of an input element within a mat-form-field when the page loads?

I'm looking to create an HTML element where the default data (stored in the variable 'preselectedValue') is automatically filled into the input field when the component loads. The user should then be able to directly edit this search string. ...

Using Three.js to extract Vertex Colors based on the z-coordinate of Vectors

Here is a sample: http://jsfiddle.net/c3shonu7/1/ The code demonstrates the creation of a BufferGeometry object by cloning an IcosahedronBufferGeometry's vertices. The goal is to apply a color gradient to the subdivided icosahedron, with lighter shad ...

The geocomplete function is not available for use with autocomplete

Hey there, I'm encountering an issue with autopopulated code. I keep getting the error "geocomplete is not a function" when trying to use it locally (in a separate file), but oddly enough it works fine for me in that context. Any idea what might be ca ...

What is the best practice for updating state immutably in React using Redux and Redux Toolkit?

As I delve into learning Redux, I've come across a method called addPosts which allows me to add posts to my list. Here's how I'm implementing it: import { createSlice } from "@reduxjs/toolkit"; const initialState = [{ number: 1 } ...

Maintain the current application state within a modal until the subsequent click using Jquery

Due to the challenges faced with drag and drop functionality on slow mobile devices, I am considering implementing a modal approach for moving elements from one place to another. Here is how it would work: When a user clicks on an item, it is visually ma ...

Can someone guide me on the process of opening and closing a Material-UI Dialog within a Meteor/React application?

I'm attempting to create a dialog with a form that pops up when the user clicks a button. I followed the example on the Material-UI Dialog site for creating a button to open the dialog and adding a TextField within it. This is being done using Meteor ...

Tips for updating a URL using data obtained from a JSON response

As I loop through an array from JSON, I extract all the necessary information. For example, if I have cards for blog posts that include the title, short description, published date, and URL. When clicking on a card, it redirects to a corresponding page ba ...

Even with explicit waiting, Selenium is unable to locate an element on an Ajax page

I'm attempting to automate the process of updating fields within a web application, where the URL remains unchanged after logging in. Here's what I have coded so far: from selenium import webdriver from selenium.webdriver.common.keys import Key ...

Where should I place my .json file to integrate Google Sheets data into my Flask web app successfully?

I'm currently in the process of setting up a web application that pulls data from Google Sheets and presents it. I came across the idea after watching a video by Twilio, which I successfully implemented on my local machine. However, I am facing diffic ...

Issues encountered when updating values in MaterialUI's TextField using Formik

Within my React functional component, I utilize Formik for form management and MaterialUI V5.10 for styling. The form includes TextField elements and a Canvas element. I am encountering two issues... Despite setting initial values in Formik, the TextFiel ...

Error encountered: Invalid symbol detected ('<') while attempting to parse JSON in an Angular application

I am experiencing an issue with my Angular code when trying to submit a form. Upon clicking the submit button, an error saying JSON Parse error: Unrecognized token '<' appears, and empty records are being saved in the database. I have included ...

The issue of CSS transitions flickering in Internet Explorer

Can someone help me troubleshoot an issue with this code in Internet Explorer? CSS: .nav-fillpath a { width: 100px; height: 100px; position: absolute; display: block; bottom: 0%; left:0; right:0; color: #3e3e3e; margin ...

tips for maximizing the safari browser window during automation testing

My current setup involves using Java and Selenium WebDriver for web automation. One issue I've encountered is that for Safari browser version 10.1, I need the browser to be in full screen mode before the test starts. driver.manage().window().maximize ...

Using JavaScript and PHP to dynamically update a field based on two input values within a row of a table

Currently in the process of developing a dynamic profit margin calculator for a personal project. Overview Data is retrieved from a database table using SQL and PHP After necessary validations, the data is dynamically displayed as rows in an HTML table ...

Displaying the format when entering a value with react-number-format

How to Display Format Only After Full Value Inserted in react-number-format I recently implemented the react-number-format package for formatting phone numbers. import { PatternFormat } from 'react-number-format'; <PatternFormat value={v ...