Home > Software design >  How to display array element on click event with D3JS
How to display array element on click event with D3JS

Time:11-04

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.

CodePudding user response:

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:

Show code snippet

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">
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related