Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you make a picture follow your mouse pointer with jquery?

Tags:

jquery

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.

like image 589
Majid Fouladpour Avatar asked Nov 05 '09 01:11

Majid Fouladpour


2 Answers

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.

like image 104
Majid Fouladpour Avatar answered Dec 08 '22 00:12

Majid Fouladpour


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.

like image 34
James Black Avatar answered Dec 07 '22 23:12

James Black