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