Published
Edited
Oct 21, 2021
Fork of Drag & Click
1 fork
Insert cell
Insert cell
circles = d3.range(20).map(i => ({
x: Math.random() * (width - radius * 2) + radius,
y: Math.random() * (height - radius * 2) + radius,
index: i
}));
Insert cell
chart = {
const svg = d3.create("svg")
.attr("viewBox", [0, 0, width, height])
.attr("stroke-width", 2)
.attr('id', 'chart')

svg.selectAll("circle.point")
.data(circles)
.join("circle")
.attr('class', 'point')
.attr("cx", d => d.x)
.attr("cy", d => d.y)
.attr("r", radius)
.attr("fill", d => d3.schemeCategory10[d.index % 10])

const line = svg.append('line')
.attr('x1', width / 2)
.attr('x2', width / 2)
.attr('y1', 0)
.attr('y1', height)
.attr('fill', 'none')
.attr('stroke', 'black')
.attr('stroke-width', 15)
.call(drag)
.on("click", clicked);

function clicked(event, d) {
if (event.defaultPrevented) return; // dragged

// d3.select(this).transition()
// .attr("stroke", "skyblue")
// .attr("stroke-width", 40)
// .transition()
// .attr("stroke", "black")
// .attr("stroke-width", 15)
}

return svg.node();
}
Insert cell
drag = {

function dragstarted() {
// d3.select(this).attr("stroke", "red").attr('stroke-width', 20);
}

function dragged(event, d) {
d3.select(this).raise().attr("x1", event.x).attr("x2",event.x)//.attr("y1", d.y = event.y);
}

function dragended(event, d) {
d3.select(this).attr("stroke", "black").attr('stroke-width', 15);
const bndryXPos = event.x;
console.log("x pos", bndryXPos);
// bind circle's position to data
d3.select('#chart')
.selectAll("circle.point")
.join(circles)
.each(function (d) {
d.group = d.x <= bndryXPos ? 0 : 1;
});
// recolor circles according to rel position to bndry
d3.select('#chart')
.selectAll('circle.point')
.transition()
.attr('fill', d => d.group === 0 ? 'red' : 'blue')
}

return d3.drag()
.on("start", dragstarted)
.on("drag", dragged)
.on("end", dragended);
}
Insert cell
height = 600
Insert cell
radius = 20
Insert cell
d3 = require("d3@6")
Insert cell

One platform to build and deploy the best data apps

Experiment and prototype by building visualizations in live JavaScript notebooks. Collaborate with your team and decide which concepts to build out.
Use Observable Framework to build data apps locally. Use data loaders to build in any language or library, including Python, SQL, and R.
Seamlessly deploy to Observable. Test before you ship, use automatic deploy-on-commit, and ensure your projects are always up-to-date.
Learn more