Looking for a simple method to link JSON data to an svg element through Javascript?

Looking to harness the power of SVG for a basic graph creation, but uncertain about the process of assigning JSON data dynamically using a 'for loop' to draw rectangles within SVG. Seeking guidance on setting up 1 loop to assign each value for drawing rectangles that will be appended to the SVG element.

<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
window.onload = function(){
var data = [  
{   
    "srno" : 1 ,
    "status" : "production" , 
    "duration" : 30,
    "color" : "#00ff00",
},
{
    "srno" : 2 ,
    "status" : "idle" , 
    "duration" : 5 ,
    "color" : "#ff0000"}];
  //Make an SVG Container
var svgContainer = d3.select("body").append("svg")
.attr("width", 720)
.attr("height", 50);
 //Draw the Rectangle
 var rectangle = svgContainer.append("rect")
.attr("x", 0)
.attr("y", 0)
.attr("width", machines [1].duration)
.attr("height", 50)
.attr("fill","green");//Here I want the color from JSON object
//And I want duration to be the width property, 
//Status be the tooltip , which is not working 
</script>   

Answer №1

Check out this informative article for a detailed guide on how to achieve that:

http://tympanus.net/codrops/2013/11/05/animated-svg-icons-with-snap-svg/

You can easily access the source files. Look for the json file in the "js" directory which contains svg data.

Consider using Snap.svg as it can greatly assist you with this task:

I hope this information proves valuable to you!

Answer №2

Behold the successful outcome!

<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
window.onload = function(){
var data = [  
{   
"srno" : 1 ,
"status" : "production" , 
"duration" : 30,
"color" : "#00ff00",
},
{
"srno" : 2 ,
"status" : "idle" , 
"duration" : 5 ,
"color" : "#ff0000"}
];
for ( var i = 0 ; i < data.length ; i++){
var rect = document.createElementNS(svgNS,'rect');
var width = data [i].duration ;
rect.setAttribute('x',20);
rect.setAttribute('y',10);
rect.setAttribute('width',data[i].duration);
rect.setAttribute('height',50);
rect.setAttribute('fill',data[i].color);
}};
</script>

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

Leveraging the Power of CSS in Your Express Applications

Struggling to make my CSS links functional while working on localhost. Currently, when I view Index.html on my server, it displays as plain text without any styling. Even after trying the express middleware, the CSS files are still not being served, result ...

Building forms within an AngularJS directive

I recently developed an AngularJS directive that includes a form. This form consists of a required text field along with two additional child forms. Each child form also contains a required text field. The distinguishing factor between the two child forms ...

Generating varying commitments from one function

I have encountered an issue where I am returning a promise from a function that is part of a $q.all array. Initially, this setup works perfectly on page load. However, the challenge arises when I need to call this function multiple times afterward to updat ...

Wait for response after clicking the button in Vue before proceeding

When the button is clicked for the first time and the data property is empty, I need to pause the button click code until an ajax response is received. Currently, when I press the button, both wait and scroll actions happen immediately without waiting for ...

Create a TypeScript class object with specified constructor arguments

I've been working on a function that is supposed to execute the init method of a class and then return an instance of that class. However, I'm running into issues with maintaining the constructor and class types. This is what I have tried so far ...

Every time I hit the refresh button, I find myself forcefully logged out

After switching from using localStorage to cookies in my React JS web app, I am experiencing an issue where I get logged out whenever I refresh the page. Even though the cookies are still stored in the browser, the authentication process seems to be failin ...

What steps can I take to decrease the padding of this footer?

Is there a way to reduce the height of the footer so it doesn't dominate the screen on both large and small devices? import { Container, Box, Grid } from "@material-ui/core"; const Footer = (props) => { return ( <footer> ...

Make JQuery send a POST request instead of OPTIONS when making a cross-domain call

Currently, I am facing a challenge where I need to send an ajax POST request (json) to a different domain. However, since I am testing on localhost and do not have access to the server yet, everything is a bit more complicated. Unfortunately, it is not po ...

"Seeking to access the call stack in the VSC debugger? Unfortunately, console.trace() turns out to

When I'm stopped in the VSC debugger, I am unable to retrieve the call stack using console.trace(). https://i.stack.imgur.com/f6jke.png ...

I'm sorry, but we were unable to locate the module: Error: Unable to find 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib'

Encountering an error when building a react app on production: Module not found: Error: Can't resolve 'fs' in '/usr/src/app/node_modules/jpeg-exif/lib' Node Version: Node version 18 Steps taken in Docker Production: npm install - ...

Why is my HTTP request callback not being executed?

I've been trying to send an HTTP POST request to a 3rd-party API using a promise method. Oddly enough, the callback function never seems to run, even though when I test the code on its own, the API call is successful. Node.js and the concept of an e ...

How to Call a Nested Object in JavaScript Dynamically?

var myObj = { bar_foo : "test", bar : { foo : "hi there"; }, foo : { bar : { foo: "and here we go!" } } } How can we achieve the following: var arr = [["bar", "foo"], ...

The console object in Chrome_browser is a powerful tool for debugging and

Having difficulty saving an amchart graph to the localstorage and retrieving the data successfully. https://i.stack.imgur.com/lJ3bJ.png In the original object, there is a mystery b, while in the new object, it appears as a normal object. In Internet Expl ...

Interactive button visual effect

I have a piece of code that currently plays audio when I click on an image. However, I am looking to modify it so that not only does clicking on the image play the audio, but it also changes the image to another one. Can anyone assist me with this? Here i ...

Extracting the initial data from a JSON stream with jq

What could be the reason behind first(select(.updated_at=="2019-06-03T16:36:53.194Z")) providing more than one result with the given input? {"_id":"a","updated_at":"2019-06-03T16:36:53.194Z"} {"_id":"b","updated_at":"2019-06-03T19:27:15.192Z"} {"_id":"c", ...

Having trouble with a basic select tag and options not functioning properly in Chrome browser

I encountered an issue where I am unable to expand a simple select tag in Chrome. <select id="filterCategory" class=""> <option>1</option> <option>2</option> <option>3</option> <option>4</option ...

Utilize jQuery to export HTML or JSON data to an Excel spreadsheet

I am looking for a way to export json or html data to an excel sheet using only html and jquery, without involving any server code. I have found some fiddles that allow me to download the excel sheet successfully, but unfortunately, none of them work in In ...

The responseXML received from an Ajax/POST request is missing only when using Chrome browser

While working on a "simple" JavaScript application, I noticed an unusual behavior. A function in the script sends a request with parameters to a .php page using the traditional Ajax/POST method. function sendRequest(params, doAsync, onSending, onDone) { v ...

The trick to keeping a div open without it closing until the page is refreshed

I am currently working on a project that involves creating an interactive map with dots. Each dot, when clicked, should trigger the display of a form related to that specific dot within a <div>. My challenge is ensuring that once a dot is clicked an ...

Showing JSON response on an HTML page using AngularJS

I have limited experience with JavaScript and/or Angular, but I am required to utilize it for a research project. My task involves showcasing the JSON data returned by another component on a webpage. Here is how the process unfolds: When a user clicks on ...