Skip to content

Instantly share code, notes, and snippets.

@codetricity
Last active October 12, 2018 13:31
Show Gist options
  • Select an option

  • Save codetricity/c2b70880b4d27b228bce9e652e133e63 to your computer and use it in GitHub Desktop.

Select an option

Save codetricity/c2b70880b4d27b228bce9e652e133e63 to your computer and use it in GitHub Desktop.
2nd exercise on drag - change selected circle color

Drag Start End

  1. Create new functions for dragStart and `` dragEnd``
  2. initially print out 'drag started' and 'drag ended'
  3. Use events start and end to trigger the function
  4. change color of circle when drag starts
  5. revert color back when drag ends

you can identify the circle you have chosen in the function with

d3.select(this)

If you assign the above line to a variable such as current, you can then do

current.style('fill', 'red')
var svg = d3.select('body').append('svg')
.attr('width', '300')
.attr('height', '300')
.style('border', '2px solid');
var drag = d3.drag()
.on('drag', dragged)
.on('start', dragStart)
.on('end', dragEnd);
var circle = svg.append('circle')
.attr('cx', '100')
.attr('cy', '100')
.attr('r', '32');
circle.call(drag);
function dragged(d) {
circle
.attr('cx', d3.event.x)
.attr('cy', d3.event.y);
}
function dragStart() {
current = d3.select(this);
current.style('fill', 'red');
}
function dragEnd() {
d3.select(this)
.style('fill', 'black');
}
/** additional references
* moving rect and text as a group
* https://bl.ocks.org/d3noob/204d08d309d2b2903e12554b0aef6a4d
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment