user1938653 user1938653 - 3 months ago 28
jQuery Question

Make a dynamic image follow mouse

There is this version of image following mouse:

http://jsfiddle.net/BfLAh/1/

And I've tried to make it work with a dynamically loaded image like this:

var a = new Image();
a.src = 'https://upload.wikimedia.org/wikipedia/commons/6/6a/This_is_a_demo_blue_dot.png';
a.onload = g;

function g(){
$(document).mousemove(function(e){
$(a).css({left:e.pageX, top:e.pageY});
});
}


But it doesn't work. I need it to work this way since I am going have to draw it on canvas too later on.

I guess the problem is that jQuery can't find the image that way, so how do I make it work?

Answer

Set id to the element and append it in the DOM

As position : absolute; is being applied through css, applying id over image element is essential.

var a = new Image();
a.id = 'image';
a.src = 'https://upload.wikimedia.org/wikipedia/commons/6/6a/This_is_a_demo_blue_dot.png';
$('body').append(a);
a.onload = g;

function g() {
  $(document).mousemove(function(e) {
    $(a).css({
      left: e.pageX,
      top: e.pageY
    });
  });
}
#image {
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>

Comments