1
votes

I need to drag a table cell and show its ghost under the mouse pointer while dragging. The table is entirely generated with d3.js. When I set the draggable attribute to true on the appropriate cells the ghost image appears as expected.

 rows
    .append("td")
    .text(function (d) {return d.name;})      
    .attr('draggable', 'true');

But since I need the dragging to affect other elements on the page as well (set different styles, filter selections, and so on), I call d3.behavior.drag() and implement the dragstart, drag and dragend functions.

.call(d3.behavior.drag()
   .on('dragstart', function () {
      d3.select(this)
         .classed('dragged', true)
         .style('font-style', 'italic')
         .style('color', 'grey');
   })
   .on('drag', function () {
      d3.select('#drop-target')
         .style('background-color', 'green');
   })
   .on('dragend', function () {
      d3.select(this)
         .classed('dragged', false)
         .style('font-style', 'normal')
         .style('color', 'black');
      d3.select('#drop-target')
         .style('background-color', 'yellow');
   })
);

The problem is that d3.behavior.drag() seems to override the creation of a ghost image and now there are no visual queues that an element is being dragged. What am I doing wrong?

Here is a fiddle: http://jsfiddle.net/00drii/5p3dqx62/1/

1

1 Answers

1
votes

Instead of registering the listeners to the drag behavior add it to the selection.

rows.append('td').html(function (d) {
     return d.type;
 })
     .style('font-style', 'italic');
 rows.append('td').text(function (d) {
     return d.name;
 })
     .attr('draggable', 'true')

     .on('dragstart', function () {
     d3.select(this)
         .classed('dragged', true)
         .style('font-style', 'italic')
         .style('color', 'grey');
 })
     .on('drag', function () {
     d3.select('#drop-target')
         .style('background-color', 'green');

 })
     .on('dragend', function () {
     d3.select(this)
         .classed('dragged', false)
         .style('font-style', 'normal')
         .style('color', 'black');
     d3.select('#drop-target')
         .style('background-color', 'yellow');

 });

Working code here

Hope this helps!