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++
}
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