Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

122
Views
D3.JS Click Event problem, using a svg map

Hi I'm fairly new to the D3 library, and I cannot figure out how to get a click event to work when I'm clicking on the country, I understand the 'd' variable contains the country information but how do I get it to console log on click. I've tried a few methods but cant figure it out. any help appreciated

   const svg = d3.select("svg"),
           width = +svg.attr("width"),
           height = +svg.attr("height");

   // Map and projection
   const projection = d3.geoNaturalEarth1()
           .scale(width / 1.5 ) // Lower the num closer the zoom
           .translate([200, 700])  // (Horizontal, Vertical)

   // Load external data and boot
   d3.json("https://raw.githubusercontent.com/holtzy/D3-graph-gallery/master/DATA/world.geojson").then( function(data) {

     // Draw the map
     svg.append("g")
             .selectAll("path")
             .data(data.features)
             .join("path")
             .attr("fill", "#348C31") // Color Of Country
             .attr("d", d3.geoPath().projection(projection))
             .style("stroke", "white")// Border Lines
             .append("title")
                .text(d => console.log(d))
       //Want to run on click of country,
   })

   const $countyPaths = svg.append("g")
   .selectAll("path")
   .data(data.features)
   .join("path")

   $countyPaths
       .attr("fill", d => color(data.get(d.id)))
       .attr("d", path)
       .append("title")
   
   $countyPaths.on('click',d=>console.log(d.id))

   function buttonClick() {
       window.alert("Boom");
   }



 </script>
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

d3 provides the .on(event, fx(event, d)) method in order to handle events. To log the country, you could do then the following:

svg.append("g")
         .selectAll("path")
         .data(data.features)
         .join("path")
         .attr("fill", "#348C31") // Color Of Country
         .attr("d", d3.geoPath().projection(projection))
         .style("stroke", "white")// Border Lines
         .on("click", (_, d) => console.log(d))

Note that the first thing that the function from the event listener will receive is the event info, and the second one the data

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!