I want that the div I created will move when the mouse is getting near to him.
Here is the fiddle link: http://jsfiddle.net/jLAq3/2/
Basic starting code (because I don't have a clue how to do it):
$('#leaf').(); I want that the div I created will move when the mouse is getting near to him.
Here is the fiddle link: http://jsfiddle.net/jLAq3/2/
Basic starting code (because I don't have a clue how to do it):
$('#leaf').(); This is a start. Every time the mouse is moving outside the leaf then a message appears.
$('body').mousemove(function(e){ var w = $('#leaf').outerWidth(), h = $('#leaf').outerHeight(), x = e.pageX, y = e.pageY; if(x > w && y > h) { console.log("The leaf is moving"); } }) Furthermore you can apply some css with js to the leaf for movement etc. In a more complex example you have to spot more carefully the position and not simply rely on the width and the height of the image.
Here is a start.
$( 'body' ).mousemove( function( event ) { if( isNear( $( '#near' ), 20, event ) ) { $( '#near' ).html( 'is near!' ); } else { $( '#near' ).empty(); }; } ); function isNear( $element, distance, event ) { var left = $element.offset().left - distance, top = $element.offset().top - distance, right = left + $element.width() + ( 2 * distance ), bottom = top + $element.height() + ( 2 * distance ), x = event.pageX, y = event.pageY; return ( x > left && x < right && y > top && y < bottom ); }; Have fun!
Here is a basic working example of how you actually would do all that http://jsfiddle.net/jLAq3/10/
var leafX = 0, leafY = 0; $('#leaf').css({position: 'relative'}); $(document).mousemove(function(e){ var offset = $('#leaf').offset() ,x1 = offset.left - 20 ,x2 = offset.left + $('#leaf').width() + 20 ,y1 = offset.top ,y2 = offset.top + $('#leaf').height() + 20 ,center, mousePos ; if(e.pageX > x1 && e.pageX < x2 && e.pageY > y1 && e.pageY < y2) { center = (x2 - x1) / 2; mousePos = e.pageX - x1; if(mousePos < center) { leafX += 20; } else { leafX -= 20; } center = (y2 - y1) / 2; mousePos = e.pageY - y1; if(mousePos < center) { leafY += 20; } else { leafY -= 20; } } $('#leaf').css({ top : leafY + 'px', left : leafX + 'px'}); }); But you should really learn the basics of DHTML before jumping into things, for example the difference between position absolute and relative, how to actually move HTML elements, layering, event binding etc.
Here are couple of good resources:
http://www.quirksmode.org/sitemap.html
http://www.w3schools.com/