Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

100
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda