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

96
Views
How to display array element on click event with D3JS

I just started learning D3Js and I'm struggling with a basic idea.

Let's say I have an array:

let arr = [a, b, c, d];

And, I have a button in the HTML

<input type="button" id="btn" value="Click">

Using the d3js, I want to print out (e.g., console.log) to print elements in the array one by one in order. In other words, the first button click prints 'a', the second click 'b', and so on then starts from 'a' again after hitting the last element.

Below is my attempt, which isn't working.

d3.select("#btn").data(arr).enter().on("click", function(d) { return console.log(d)});

Can someone help me with the idea of how I can get this working?

Thanks.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

If I understand you correctly we can do this fairly easily (with or without D3). As you're asking about D3, I'll show a soluation with it.

You are using .data() and .enter() - these are used when you want to create an element for every item (datum) in the data array - but you only have one element, that already exists. Since we don't need to enter anything and we have only one datum, these two methods aren't what you are looking for. Also, enter is usually followed up with .append() which creates the entered elements - without that you aren't assigning the on listener to any clickable element.

Instead, we can bind an individual datum containing an array of values to the button:

 .datum(arr)

But, we can create a more useful datum than that by also including a property for the current index so that everything we need is self conained:

.datum({i:0,arr:arr})

Then we can assign a click listener to the button which accesses the datum, logs the value of arr[i] and increments i. Below I use the modulus operator to avoid ever having to reset i to 0:

let arr = ["a", "b", "c", "d"];

d3.select("input")
  .datum({i:0, arr:arr })
  .on("click", function(d) {
    console.log(d.arr[d.i++%d.arr.length])
  })
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>
<input type="button" id="btn" value="Click">

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!