Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize element and start dragging with just one click

At mousedown I want to inject a new element in the DOM and start dragging it immediately (i.e. trigger dragstart), without clicking the new element again.

I am using d3.js a lot in my project. But I don't know if I can trigger the dragstart event by using d3, so I tried using jQuery:

$("circle#pen").trigger("dragstart");

But this doesn't work.

Here is a link to a jsFiddle, where I demonstrate my problem by trying to create a "pen" at mousedown, and if the user drags the pen it draws a line. At dragend the pen is removed and the line fades away. But the pen has to be initialized, and then it can be dragged by a new click. This is just for demonstrating the problem.

Here is a related question for jQuery, but there are no good answer to it.

like image 427
swenedo Avatar asked Nov 02 '22 19:11

swenedo


1 Answers

I found a jQuery library called jquery-simulate. By using that I solved the problem like this:

var coords = {  
    clientX : d3.event.x,
    clientY : d3.event.y
};

d3.select("g#selects").append("circle")
    .attr("id", "pen")
    .attr("r", 10)
    .attr("cx", coords.clientX)
    .attr("cy", coords.clientY)
    .call(dragPen);

$("circle#pen").simulate("mousedown", coords);

The element #pen now gets injected and a drag is initiated with just one click. If you know a solution without a library like query-simulate, please let me know.

like image 134
swenedo Avatar answered Nov 09 '22 10:11

swenedo