9

I find drag-and-drop difficult (you know, keeping the mouse button depressed while moving), and want to offer a 'select and drop' where a user clicks on an icon and clicks again on the drawing-plate to drop the corresponding element (a picture).

How do you do that with jquery?

Thanks.

Edit: I have two divs, an icons plate to select elements from, and a drawing plate where pictures are dropped. When the mouse enters the drawing plate I want a 50% opacity of the bigger image follow the mouse pointer so that the user knows by clicking where it is going to be dropped and if it overlaps with anything already on the drawing board.

Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127

2 Answers2

28

The answer (using James Black's help) is:

HTML

  <div id="sketch"></div>
  <img src="cat.jpg" class="follow" style="position: absolute;"/>

JQuery

$("#sketch").mousemove(function(e){
      $('.follow').css({'top': e.clientY - 20, 'left': e.clientX - 20});
});

Jsbin demo here.

Majid Fouladpour
  • 29,356
  • 21
  • 76
  • 127
3

Just store the element in some variable that is accessible to the click event.

So, have an onclick on every image: $('img').bind('click', function(e) { ... }); Then, when they click, just store the targetEvent somewhere and bind a click event to the drawing-plate.

An interesting way would be to use a closure and bind that particular targetEvent so that in the event of a click on the drawing-plate you will know which one to move, but as long as you know, then you will just use an animation to move the img over to the new location.

I forgot, you will also need to ensure that when an image is clicked on that the event handler that is already on the drawing-plate is removed before binding a new one.

James Black
  • 41,583
  • 10
  • 86
  • 166
  • I guess that is the way to do it in javascript without a framework. I hoped there would be an easier way utilizing the powers of jquery. Also, you click the icon but you drop the image and they are not the same. – Majid Fouladpour Nov 05 '09 at 01:58
  • jQuery makes this easier to do, in that it abstracts out a lot of the work of making it cross-platform. It would be easy to implement, if it takes less than 30 minutes I just do it myself. If you click the drawing-plate, after clicking on an image, you can clone or move the img to the correct place, as though it was done with DnD. – James Black Nov 05 '09 at 02:03
  • The whole idea is having an image follow your mouse pointer while it is within the drawing-plate. cloning the image to be placed on the plate is not a problem. – Majid Fouladpour Nov 05 '09 at 02:07
  • 1
    So you just use the mousemove event and just keep moving the image as the cursor moves on the drawing-plate, so clicking on it would lead to two events being bound. – James Black Nov 05 '09 at 02:14
  • Your mention of 'mousemove event' event put me on the right track, thanks! – Majid Fouladpour Nov 05 '09 at 03:32