How can i create moving element using mouse position, like at http://fieroanimals.com/?

16,138

Solution 1

$(document).ready(function(){
      $('div.moveAble-container').mousemove(function(e){
            var y = e.pageY;
            var x = e.pageX;                    
            $('div.moveAble').css({'top': y}); 
            $('div.moveAble').css({'left': x});

      });
    });

Solution 2

$('div.images').mousemove(...) implies that it will only detect mouse movements that are over top of div.images.

$('html') will detect mouse movement over the whole page.

jsFiddle Example

Depending on your needs, you may want apply the X-coordinate to your CSS left property and Y-coordinate to CSS top. (You have it the other way around in your question).

Share:
16,138
Alexander Shvets
Author by

Alexander Shvets

Updated on June 09, 2022

Comments

  • Alexander Shvets
    Alexander Shvets almost 2 years

    I want to create div element with an image inside, and change it position with coordinates from mouse position. There is a few jquery-pluings for creating 3d effect, but i need only move on X and Y coordinates. Also, do that in limit of div element.

    I got next code:

    $('div.images').mousemove(function(e){
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            $('div.images').css({'top': x,'left': y}); 
        });
    

    In CSS div.images have absolute position. When i move my mouse is not changing position, but when I delete position in CSS it's apply changes to the style of element, but no change position.

    Giv me some advise what I need to do.

    At http://fieroanimals.com/ that realised on Flash, but I want do that on JQuery.

  • Alexander Shvets
    Alexander Shvets almost 12 years
    Yes. I got that. It's my mistake. On more: How i need to change coordinates for image, so i can move like at fieroanimals.com, for vertical images, for example.
  • vinni
    vinni over 7 years
    x and y are inverted. It should be like that: $('div.images').css({'top': y,'left': x});