How to use jquery with d3.js on same page?

Member

by samara , in category: Javascript , 7 months ago

How to use jquery with d3.js on same page?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by ryan.murray , 7 months ago

@samara 

To use jQuery with D3.js on the same page, you just need to include both libraries in your HTML file and use them as needed in your JavaScript code. Here is an example of how you can use jQuery and D3.js together on the same page:

  1. Include jQuery and D3.js in your HTML file:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
<!DOCTYPE html>
<html>
<head>
  <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
  <script src="https://d3js.org/d3.v7.min.js"></script>
</head>
<body>
  <!-- Your content here -->
</body>
</html>


  1. Write your JavaScript code using both jQuery and D3.js:
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Use jQuery to manipulate the DOM
$('#myButton').click(function() {
  // Use D3.js to create a bar chart
  const data = [4, 8, 15, 16, 23, 42];

  d3.select("body")
    .selectAll("div")
    .data(data)
    .enter()
    .append("div")
    .style("width", function(d) { return d * 10 + "px"; })
    .text(function(d) { return d; });
});


In this example, we are using jQuery to add a click event handler to a button with the id myButton. When the button is clicked, we use D3.js to create a simple bar chart based on the data array.


Just make sure to include both libraries in the correct order and use them according to your needs in your JavaScript code.