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

What is the best way to handle and work with the JSON response from Twitter's API?

I am currently working with the Twitter API (version 1.1) in PHP and trying to extract a specific variable from the JSON response. The $mentions variable represents the result of parsing JSON data returned by a GET statuses/mentions_timeline request. Here ...

Leveraging the power of LocalStorage in Ionic 2

Trying to collect data from two text fields and store it using LocalStorage has proven tricky. Below is the code I have set up, but unfortunately it's not functioning as expected. Can you provide guidance on how to resolve this issue? In page1.html ...

The oncanplaythrough event is not functioning properly in Internet Explorer

I am facing an issue where the beep sound trigger upon receiving an API response works perfectly in Chrome and Firefox browsers, but unfortunately, it does not work in Internet Explorer. if ($scope.totalQueueList) { var audio = new Audio(); audio.s ...

When trying to access $model.show() in Vue.js, the returned model is showing as undefined

I'm running into a console error message every time I try to click the button for $model.show('demo-login'): TypeError: Cannot read property 'show' of undefined Error output when the button is clicked: TypeError: Cannot read prop ...

"Utilizing a Handlebars Helper to Evaluate if Two Values (v1 and v2) are Equal, and Displaying Content from

To make the actual call, I require something along these lines: <script id="messagesTemplate" type="text/x-handlebars-template"> {{#each messages.messages}} {{#each to}} {{#ifCond username messages.sessionUserName}} <h1> ...

Error encountered while updating in the midst of an ongoing state transition, e.g. within the `render` method

class MyComponent extends React.PureComponent { constructor(props) { super(props); this.state = { obj: [], externalObj: [], }; } fetchData = (external) => { ... arr = arr.filter(a => a.toLowerCase().includes(&ap ...

An error occurred with Express and Passport: ['ERR_HTTP_HEADERS_SENT']

Currently, I am diving into an ebook tutorial and have encountered a roadblock in a particular piece of code. The code is designed to take a username and password in JSON format through Insomnia or Postman, and it should return a login success cookie. Howe ...

Tips for incorporating a custom CSS design into a jQueryUI tooltip

I am struggling to apply my custom CSS class on top of the jQueryUI tooltip. Although the tooltip is displaying correctly, my styles are not being applied. Here is the code I'm using: $(document).ready(function () { $("#roles").tooltip({ content: ...

Ascending to the Peak within a div

<script type="text/javascript"> $(document).ready(function(){ updateContent(); }); function updateContent(){ $('#mainDiv').load('home.php', function(){ scrollToTop(); }); } ...

Tips for Using Sed to Remove the Final Character of the Previous Line

My goal is to remove a line with the last character of the previous line using sed: This is an example of a json file : { "name":"John", "age":"16", "country":"Spain" } I want to delete the "country" field from all entries in the file. To do this, I nee ...

Can I request my information to be formatted in JSON rather than XML in Oracle 11g?

I have a current situation where my API is built using PL/SQL with Oracle 11g, and it currently generates data in XML format. My task now is to convert this XML output into JSON. However, I've discovered that Oracle 12c introduced native JSON support. ...

Utilize jQuery and AJAX to fetch a JSON file by passing parameters

Can anyone guide me on how to call a JSON file with parameters? In the past, I've used PHP and converted it to JSON. Below is the jQuery code snippet: $("#btnKeyword").on("click",function(){ var param = document.getElementById('inputKeyword& ...

Restart the _.after function counter

Despite my efforts to search online, I couldn't find a solution for resetting the _.after counter once the code inside has been executed. The goal here is to have the alert box appear only on every 5th click of the button: var cb; cb = _.after(4, fu ...

Having trouble utilizing props with Vue axios? Running into an undefined error? Unsure how to properly use props with axios?

https://i.stack.imgur.com/QfCDG.png There seems to be an issue with my saveComment() function in CommentList.vue. It can't find the comments' post_id and causes this error: CommentList.vue?6c27:107 Uncaught TypeError: Cannot read properties of u ...

Adding a listener to an element within a loop

I'm currently exploring a way to add an event listener in my script. Here's the variable I have: var inputs = data.context.find(':input').not(':button'); Following that, I have a FOR loop where I utilize this variable to ap ...

Using Spring MVC and Jackson to send a date as JSON

I am facing a challenge with passing a java.util.Date field from a client to a Spring controller. Whenever I make the request, the controller returns HTTP 415 error code. Despite trying various solutions like adding a custom serializer, the issue persists. ...

How to retrieve a refined selection of items

In my scenario, there are two important objects - dropdownOptions and totalItem The requirement is as follows: If 12 < totalItems < 24, then display "Show 12, Show 24" If 24 < totalItems < 36, only show "Show 12, Show 24, Show 36" This patte ...

Additional forward slashes in the JSON response

Within the database fields are: { "email", "color" } However, when attempting to display this using application/json' => \yii\web\Response::FORMAT_JSON, additional slashes appear in the string. [ "Verify", "{ \"ema ...

Understanding the scope of variables in HTML files, JavaScript files, and PHP files when echoing statements

Is there a way to define a global javascript variable that can be accessed from multiple places within an HTML page? I need the variable to be accessible in three specific locations: Within the code of the HTML page favorites.php. Inside a separate javas ...

What's the best way to transfer a variable from a PHP file to a jQuery AJAX file so that it can be used as the URL parameter when sending

I am just starting out with javascript, jquery, and ajax. Unfortunately, I've encountered an issue where my code is not working as expected. Below, you can find a detailed description of my code and the problem at hand. If someone could offer some ass ...