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

175
Views
D3 onclick not using local variables

I'm trying to set this map value based on the i and j values. I thought if I passed them in they would use the local values, but I'm getting 0 and undefined for i and j when I click any of them. But the Ids are the correct values. The Arrays are populated.

let j = 1
    for (const string of yStart) {
        let i = 0;
        for (let fret of fretPositionsArray) {
            d3.select("#fretboard")
                .append('rect')
                .on("click", function (i,j) {
                    let strfrt = { str: j, frt: i}
                    music.set(Math.random(), strfrt);

                    for (let k of music.keys()) {
                       // console.log(k)
                    }
                    for (let v of music.values()) {
                        console.log(v)
                    }
                    localStorage.setItem("testMusic", JSON.stringify(Array.from(music.entries())));

                })
                .on("mouseover", function () {
                    d3.select(this).attr('fill', 'green')
                })
                .on('mouseout', function () {
                    d3.select(this).attr('fill', 'orange')
                })
                .attr("id", "S" + j + "F" + (i + 1))
                .attr('x', fret)
                .attr('y', string)
                .attr('width', fretWidthArray[i])
                .attr('height', 30)
                //.attr('stroke', 'green')
                .attr('stroke-linecap', 'butt')
                .attr('stroke-width', '1')
                .attr('fill', '#FFFAEF')
                .attr('fill-opacity', .1)
            i++
        }
        j++
    }
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

D3 dictates the parameters of your "click" callback. Remove them completely from your anonymous function:

.on("click", function () {

From the Docs on d3.selection.on

When a specified event is dispatched on a selected element, the specified listener will be evaluated for the element, being passed the current event (event) and the current datum (d), with this as the current DOM element (event.currentTarget).

So in the scope of your callback, i was now the event and j was now the datum

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!