Issue with D3 Force Directed Graph: The missing flags mystery

SCENARIO:

It is essential for each node to display its corresponding flag, however, this functionality is currently missing.


PROGRAM CODE:

body {
    font-family: Lato;
    background-color: #F5F5F5;
}

.title {
    margin-top: 30px;
    margin-bottom: 30px;
}

#results {
    text-align: center;
}

#results div {
    margin-top: 15px;
}

#results {
    background-color: white;
    margin: auto;
    width: 1200px;
    padding: 40px;
    box-shadow: 2px 2px 2px black;
}

/*!
 * Generated with CSS Flag Sprite generator (https://www.flag-sprites.com/)
 */

.flag {
    display: inline-block;
    width: 16px;
    height: 11px;
    background-image: url("https://image.ibb.co/gMUNBQ/flags.png") no-repeat;
}


/* List of different flags and their positions in the spritesheet */

.flag.flag-td {
    background-position: -240px -132px;
}

.flag.flag-pw {
    background-position: 0 -121px;
}

.flag.flag-fk {
    background-position: -32px -44px;
}
...

</script>

</html>

Answer №1

In the previous code snippet, there was an attempt to attach an HTML img element to a parent that is an SVG. It's important to note that this approach is not feasible and won't work as intended. Another suggested solution in a linked question involved using the foreignObject tag to include HTML content within the SVG, but this method is generally discouraged. Instead, the proposed solution was to create SVG patterns to facilitate the transformation of a single sprite image into appropriate coordinates for each flag. Here's how you can integrate this approach into your existing code...

Access the full code here (the stack snippet had to be edited due to size constraints).

<html>

<head>
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" integrity="sha384-rwoIResjU2yc3z8GV/NPeZWAv56rSmLldC3R/AZzGRnGxQQKnKkoFVhFQhNUwEyJ" crossorigin="anonymous">
  <link href="https://fonts.googleapis.com/css?family=Lato" rel="stylesheet">
  <style>
    body {
      font-family: Lato;
      background-color: #F5F5F5;
    }
  </style>
</head>

<body>
  <div class="body">
    <div class="container-fluid">
      <h1 class="text-center title">Countries linked by Border</h1>
      <div class="text-center">
        <div id="results"></div>
      </div>
    </div>
  </div>
  <script src="https://d3js.org/d3.v4.min.js"></script>
  <script src="https://code.jquery.com/jquery-3.1.1.min.js" integrity="sha256-hVVnYaiADRTO2PzUGmuLJr8BLUSjGIZsDYGmIJLv2b8=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/tether/1.4.0/js/tether.min.js" integrity="sha384-DztdAPBWPRXSA/3eYEEUWrWCy7G5KFbe8fFjk5JAIxUYHKkDx6Qin1DkWx51bBrb" crossorigin="anonymous"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/js/bootstrap.min.js" integrity="sha384-vBWWzlZJ8ea9aCX4pEW3rVHjgjt7zpkNpZk+02D9phzyeVkE+jo0ieGizqPLForn" crossorigin="anonymous"></script>

  <script type="text/javascript">
    // JavaScript code here
  </script>
</body>

</html>

Answer №2

The code has undergone a few modifications and now appears to be functioning correctly.

  1. The position attribute of the div that contains flags and flag class is now set to absolute.

  2. An extra <img> tag was mistakenly added, which has been removed.

  3. A typo was found - The word sim was changed to simulation in the dragstart and dragend methods.

  4. The flags div was incorrectly placed outside the svg element, so the change from

    result.select("#flags")
    to d3.select("#flags") was made.

    and more...

d3.json("https://raw.githubusercontent.com/DealPete/forceDirected/master/countries.json", function(error, json) {

  if (error) {
    return console.warn(error);
  }

  const data = json;
  const nodes = data.nodes;
  const links = data.links;

  const margin = {
    top: 0,
    right: 0,
    bottom: 0,
    left: 0
  }

  const w = 1200 - margin.left - margin.right;
  const h = 550 - margin.top - margin.bottom;

  const results = d3.select('#results')

  const svg = results.append("svg")
    .attr("width", w + margin.left + margin.right)
    .attr("height", h + margin.top + margin.bottom);

  const simulation = d3.forceSimulation()
    .nodes(nodes)
    .force("charge_force", d3.forceManyBody().strength(-3))
    .force("center_force", d3.forceCenter(w / 2, h / 2));

  const div = d3.select("body")
    .append("div")
    .attr("class", "tooltip")
    .style("opacity", 0);

  const link = svg.append("g")

  ...

});
body {
  font-family: Lato;
  background-color: #F5F5F5;
}

.title {
  margin-top: 10px;
  margin-bottom: 10px;
}

#results {
  text-align: center;
}

...

.flag {
  width: 16px;
  height: 11px;
  background: url(https://www.cs.mun.ca/~h65ped/Public/country%20data%20for%20force%20directed%20graph/flags.png) no-repeat;
  position: absolute;
}

.flags {
  position: absolute;
}

...

</html>

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

Guide on how to set a custom image as the cursor when clicking on an image through javascript

Does anyone know how to use javascript to change the cursor to a custom image by updating the cursor property of the entire page? I'm getting an error in the Chrome console that says: projetFinalPage1.html:626 Uncaught TypeError: Cannot read property ...

Utilizing jQuery and JSON to showcase the contents of an array

My goal is to display all the items in an array by utilizing JSON and jQuery from the Song of Ice and Fire API. Currently, I am only able to display one item from each of the arrays. If you want to view the codepen, click here: https://codepen.io/frederic ...

Searching in MongoDB using regular expressions, starting with the JavaScript driver in a Node.js environment

Currently, I am utilizing the JavaScript MongoDB driver from Node.js. My objective is to execute this query within my JavaScript function: db.mycollection.find({Zip:/^94404/}); Upon running the above query, the mongo client successfully retrieves 8 docum ...

React date format error: RangeError - Time value is invalid

I'm utilizing a date in my React app using the following code: const messageDate = new Date(Date.parse(createdDate)) const options = { month: 'long', day: 'numeric', hour: 'numeric', minute: 'numeric' } as const ...

Tips for collapsing a react-bootstrap accordion panel in a horizontal direction

Exploring the capabilities of the Panel component from React-Bootstrap available on this link, I am interested in implementing their accordion feature with a twist. I want the panel body (Panel.Body) to expand horizontally, opening to the right of the Pane ...

Fixing My Code with JQuery Tabs and Hyperlinking

I have come across a problem while using multiple pages with jQuery tabs. Let's consider Page1.html with #tab1 and #tab2, and Page2.html with #tab3 and #tab4. Here are the issues I am facing: 1) Within the tab content of Page1.html#tab2, there is a h ...

Iterate over Observable data, add to an array, and showcase all outcomes from the array in typescript

Is there a way to iterate through the data I've subscribed to as an Observable, store it in an array, and then display the entire dataset from the array rather than just page by page? Currently, my code only shows data from each individual "page" but ...

What steps can be taken to prevent users from dragging a page horizontally?

One function on my site involves a horizontal scroll that animates the DIV to the left when a button is clicked. The element's width is set at 18000px, ensuring it has a horizontal scrollbar that I have since disabled. Despite this, users are still ...

Guide on displaying a document in react-doc-viewer from a protected API endpoint in either Next.Js or ReactJs

I am looking to display files in my Next.JS web application using a secure API. The API provides the following data: { "name": "Test1.docx", "contentUri": "https://api.mypurecloud.ie/api/v2/downloads/x ...

Click function unresponsive following the completion of an Ajax call

I'm having an issue with my WordPress site where the JavaScript code I am using for an Ajax filter is not functioning properly once the filter is activated. Specifically, the click event is not working as expected. function addStoreLinkListeners() { ...

Unexpected values being returned by Javascript/jQuery variables

Struggling with understanding scope in JavaScript, like many others before me. It can be quite challenging to navigate through the code at times. I've reviewed previous discussions on this topic, but I'm still having trouble applying it to my spe ...

Building HTML within an Angular JS Directive

I am in the process of creating a custom directive for a basic modal window, which will be used like this: <modal content="<div class='error-text'>this is the content</div>"></modal> This should result in the following H ...

How can I incorporate the mix-blend-mode into my d3 stroke technique?

I am working with a packed circles graph that has circles with a black stroke on hover. I am interested in using the CSS property mix-blend-mode: multiply to change the circle border when hovered over. My goal is to have the stroke color be a darker shade ...

Toggle the visibility of a div using JavaScript depending on the data value

I have a collection of images displayed in div tags with data attributes. My goal is to toggle their visibility using CSS based on a match with input text. I iterate through the divs with the matching class, then loop through the words in the input array, ...

jquery unbinding events can lead to faster performance

I'm in the process of creating a content-heavy slideshow page that heavily relies on event triggers, with about half of them utilizing the livequery plugin. I'm curious if unloading these events between slides to ensure only the active slide has ...

Angular15: How can we properly provide support for legacy browsers?

I'm having issues with my Angular build on IOS12 as it's only displaying a blank page. Below are the dependencies listed in my package.json: "dependencies": { "@angular/animations": "^15.0.0", "@angular ...

The onmouseout event is triggered when the mouse leaves a table row or cell

My image has an onmouseover function that displays a table with options over the image (dimming the image). The table also has an onmouseout function to hide the table and show the image again. The issue I'm facing is that when the mouse moves between ...

Limiting access to multiple Node.js applications on a machine with multiple IPv4 addresses

Setting up a Ubuntu 19.10 machine with one to two wired network interfaces and multiple IP addresses assigned to each interface, for example, 10.0.0.1 and 10.0.0.2. Is there a way to run two identical Node.js applications where the first one uses the IP a ...

Utilize the ESLint plugin to manage unresolved import paths in Next.js modules

Utilizing module import from next and attempting to import a component as shown below: import Navbar from '@/components/Navbar/Navbar'; Upon running npm run lint, an error is returned stating: 1:20 Error: Unable to resolve path to module &apo ...

Securing a JWT token post login

I am new to NodeJS and despite trying numerous solutions, I am facing a challenge. My project involves NodeJS, MongoDB, Express, and Vanilla JS rendered through Pug with an MVC structure. Issue Current Status: I can successfully log in a user and recei ...