Centering a JavaScript object within a div

I recently delved into the world of JavaScript and decided to experiment with this graphing library.

I followed one of their example codes, and now I have a bit of a beginner-level HTML/JS question.

This is the code snippet they provided:

Upon running this code, the graph is displayed on the left side of the div element.

I am curious about how I can center align this object within the div.

I'm unsure whether achieving this requires an "HTML/CSS" solution or if it falls under a "JS task." Upon inspecting the API documentation, I couldn't find any alignment options.

I apologize for the basic nature of this question; I attempted to solve it myself but haven't had any luck so far.

<!DOCTYPE html>
  <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <title>Tutorial Demo</title>
    </head>
    <body>
      <div id="mountNode"></div>
      <script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g6-3.7.1/dist/g6.min.js"></script>
      <script>
        // JavaScript code block from the example
      </script>
    </body>
  </html>

Answer №1

simply utilize flexbox.

#mountNode{
display:flex;
justify-content:center;
}
<!DOCTYPE html>
    <html lang="en">
      <head>
        <meta charset="UTF-8" />
        <title>Tutorial Demo</title>
      </head>
      <body>
        <div id="mountNode"></div>
        <script src="https://gw.alipayobjects.com/os/antv/pkg/_antv.g6-3.7.1/dist/g6.min.js"></script>
        <script>
          const graph = new G6.Graph({
            container: 'mountNode',
            width: 800,
            height: 600,
            // Default properties for all the nodes
            defaultNode: {
              labelCfg: {
                style: {
                  fill: '#fff',
                },
              },
            },
            // Default properties for all the edges
            defaultEdge: {
              labelCfg: {
                autoRotate: true,
              },
            },
            // The node styles in different states
            nodeStateStyles: {
              // The node style when the state 'hover' is true
              hover: {
                fill: 'lightsteelblue',
              },
              // The node style when the state 'click' is true
              click: {
                stroke: '#000',
                lineWidth: 3,
              },
            },
            // The edge styles in different states
            edgeStateStyles: {
              // The edge style when the state 'click' is true
              click: {
                stroke: 'steelblue',
              },
            },
            // Layout
            layout: {
              type: 'force',
              linkDistance: 100,
              preventOverlap: true,
              nodeStrength: -30,
              edgeStrength: 0.1,
            },
            // Built-in Behaviors
            modes: {
              default: ['drag-canvas', 'zoom-canvas', 'drag-node'],
            },
          });
    
          const main = async () => {
            const response = await fetch(
              'https://gw.alipayobjects.com/os/basement_prod/6cae02ab-4c29-44b2-b1fd-4005688febcb.json',
            );
            const remoteData = await response.json();
    
            const nodes = remoteData.nodes;
            const edges = remoteData.edges;
            nodes.forEach((node) => {
              if (!node.style) {
                node.style = {};
              }
              node.style.lineWidth = 1;
              node.style.stroke = '#666';
              node.style.fill = 'steelblue';
              switch (node.class) {
                case 'c0': {
                  node.type = 'circle';
                  node.size = 30;
                  break;
                }
                case 'c1': {
                  node.type = 'rect';
                  node.size = [35, 20];
                  break;
                }
                case 'c2': {
                  node.type = 'ellipse';
                  node.size = [35, 20];
                  break;
                }
              }
            });
            edges.forEach((edge) => {
              if (!edge.style) {
                edge.style = {};
              }
              edge.style.lineWidth = edge.weight;
              edge.style.opacity = 0.6;
              edge.style.stroke = 'grey';
            });
    
            graph.data(remoteData);
            graph.render();
    
            // Mouse enter a node
            graph.on('node:mouseenter', (e) => {
              const nodeItem = e.item; // Get the target item
              graph.setItemState(nodeItem, 'hover', true); // Set the state 'hover' of the item to be true
            });
    
            // Mouse leave a node
            graph.on('node:mouseleave', (e) => {
              const nodeItem = e.item; // Get the target item
              graph.setItemState(nodeItem, 'hover', false); // Set the state 'hover' of the item to be false
            });
    
            // Click a node
            graph.on('node:click', (e) => {
              // Swich the 'click' state of the node to be false
              const clickNodes = graph.findAllByState('node', 'click');
              clickNodes.forEach((cn) => {
                graph.setItemState(cn, 'click', false);
              });
              const nodeItem = e.item; // et the clicked item
              graph.setItemState(nodeItem, 'click', true); // Set the state 'click' of the item to be true
            });
    
            // Click an edge
            graph.on('edge:click', (e) => {
              // Swich the 'click' state of the edge to be false
              const clickEdges = graph.findAllByState('edge', 'click');
              clickEdges.forEach((ce) => {
                graph.setItemState(ce, 'click', false);
              });
              const edgeItem = e.item; // Get the clicked item
              graph.setItemState(edgeItem, 'click', true); // Set the state 'click' of the item to be true
            });
          };
          main();
        </script>
      </body>
    </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

What methods is Facebook using to manage their onbeforeunload confirmation dialog?

While using Facebook on the latest Chrome browser on my Mac, I observed an interesting behavior. When I began typing in a comment box and then clicked on another link or pressed the back button, a confirmation window popped up asking if I wanted to leave: ...

Using Node.js and Express to retrieve data from a MySQL database and update a table

My .ejs file contains a form that sends data to a MySQL database and then displays two tables with the retrieved data on the same page. However, I am facing an issue where the tables do not refresh after submitting the form, requiring me to restart the ser ...

Using a CSS hack to create a border cutout

The Dilemma... I am attempting to position div elements over a border, while maintaining space on both sides of each div. Take a look at the scenario: Note the gaps surrounding the black divs. I am struggling to find a solution for this issue, aside fro ...

The icon displays correctly in Firefox but is not visible in IE

link REL="SHORTCUT ICON" HREF="/images/greenTheme/favicon.ico" type="image/x-icon" While this code functions properly in Firefox, it appears to be causing issues in Internet Explorer. Can anyone provide guidance on how to resolve the compatibility issue w ...

Interpreting binary decimal data using JavaScript

The Challenge Received data from an API contains binary information about colored points in 3D space. The goal is to decode these points and utilize them in a buffergeometry within Three.js. Working with binary formatted data is proving to be beyond my c ...

``on click of the back button of the browser, automatically submit the form

I'm facing a specific issue that I need help with. I have created a form with a hidden value, and I want it to be submitted when the user clicks the browser's back button. Although I've managed to control the backspace key, I haven't be ...

Convert the button element to an image

Can someone please explain how to dynamically change a button element into an image using javascript when it is clicked? For instance, changing a "Submit" button into an image of a check mark. ...

react component fails to rerender upon state change

I am struggling with a React functional component that includes a file input. Despite selecting a file, the text in the h1 tag does not change from choose file to test. The handleChange function is triggered successfully. A console.log statement confirm ...

Obtain specific text from elements on a website

How can I extract a text-only content from a td tag like 'Zubr Polish Lager 6%'? <td width="35%">Amber Storm Scotch Ale 6% <br/>SIZE/LIFE: 330ml <b>CASE</b> <br/>UOS ...

Angular HTTP request with form data is not functioning

I'm facing an issue with $http in angularjs : app.controller('ctrlProfil', function($scope, $http){ $scope.loginProfil = "<?= $_SESSION['login']?>"; $scope.mdpProfil = "<?= $_SESSION['mdp']?>"; $scope. ...

Ways to display notifications when the user is not actively browsing the website?

How can websites display notifications even when the user is not actively on the site? Take Facebook messenger, for instance. Even with the page closed, notifications still pop up. The same goes for Twitter, which also sends push notifications. I ...

Creating Hbbtv applications with the help of a Firefox Addon

My curiosity lies in creating hbbtv apps and I am eager to learn how to run and test a complete hbbtv application package, specifically a videoplayer with multiple html pages, utilizing the FireHBBTV plugin on Firefox. Despite my extensive search efforts ...

Implementing HTML rendering within a <script> tag using Vue.js

I'm attempting to display dynamic HTML within a script tag. As part of my project, I've created a custom data-table component and now I am trying to add a column for operations. However, I'm facing issues when trying to assign functions to ...

Arrange a List in immutable.js by using an array of index values

My scenario involves working with an Immutable list to populate a drag and drop feature. The list items do not have any ids, only indices when mapped through. const list = Immutable.List([{"alias":"cat"},{"alias":"dog"},{"alias":"rat"}]) Upon dragEnd, I ...

Position the textAngular toolbar at the bottom of the text editing interface

I want to position the textAngular toolbar at the bottom of the texteditor-div instead of the top. Despite trying various CSS modifications, I haven't been successful in achieving this. JS: var app = angular.module('myApp', ['textAngu ...

What is the best way to repair a react filter?

Recently, I successfully created a database in Firebase and managed to fetch it in React. However, my current challenge is to integrate a search bar for filtering elements. The issue arises when I search for an element - everything functions as expected. ...

The $_GET[id] function is malfunctioning within the designated div element

I'm trying to create a link with an id that points to a specific div on the same page. <a href="#?id=<?php echo $id; ?>" class="team-detail" data-reveal-id="single-news"></a> However, the id is not working in: <div id="single- ...

Customer is unable to locate the "InitializeAuthenticationService" function

After launching my application, the browser console keeps showing me three errors that all say Could not find 'AuthenticationService.init' ('AuthenticationService' was undefined). and Microsoft.JSInterop.JSException: Could not find &apo ...

Submitting data using various submit buttons in PHP

I am facing an issue with multiple submit buttons in my form, each containing hidden values that are dynamically generated. The problem arises when I can see the correct values in the HTML source code, but upon submitting one button, all other values get s ...

$rootScope undefined in an easy AngularJs Routing Demo

I've been trying to access the name and age using $scope and $rootScope, but I keep getting an error even though I'm pretty sure everything is set up correctly. Can someone please point out where I might be making a mistake? <html> <he ...