<div class="moveAble" style="position: absolute;">
<div class="info"><img src=".jpg" alt="info" /></div>
</div>
$(document).ready(function(){
$('div.moveAble').mousemove(function(e){
var y = e.pageY;
var x = e.pageX;
$('div.moveAble').css({'top': y});
$('div.moveAble').css({'left': x});
});
});
Above code is not working properly, as i move mouse pointer it move in bottom and right direction only and not top and left. and div movement is also not smooth. How do i fix this to make it work.
DEMO here
<div class="moveAble" style="position: absolute;">
<div class="info"><img src="https://pbs.twimg./profile_images/1498221863/Jodis_Gifts_logo_hi_res_normal.jpg" alt="info" /></div>
</div>
$(document).ready(function(){
$('div.moveAble').mousemove(function(e){
var y = e.pageY;
var x = e.pageX;
$('div.moveAble').css({'top': y});
$('div.moveAble').css({'left': x});
});
});
Above code is not working properly, as i move mouse pointer it move in bottom and right direction only and not top and left. and div movement is also not smooth. How do i fix this to make it work.
DEMO here
Share Improve this question edited Dec 30, 2013 at 8:58 Bug 2,5622 gold badges22 silver badges38 bronze badges asked Dec 30, 2013 at 8:55 Arya MehtaArya Mehta 1511 gold badge3 silver badges13 bronze badges 10- You have to use .animate to make smooth moment – Manish Jangir Commented Dec 30, 2013 at 8:56
- The problem is that you're handling the mousemove event on the div itself, but when you move the mouse up to the left it isn't over the div anymore. – nnnnnn Commented Dec 30, 2013 at 8:56
-
@ManishJangirBlogaddition. - No you don't: there are plenty of sites with smooth movement that don't use jQuery at all and so don't use
.animate()
. – nnnnnn Commented Dec 30, 2013 at 8:58 -
3
instead of
$('div.moveAble').mousemove
use$(document).mousemove
– skos Commented Dec 30, 2013 at 8:58 - like this jsfiddle/wUAGP/435 ? – user2587132 Commented Dec 30, 2013 at 8:59
2 Answers
Reset to default 11I suppose this is the effect you wanted http://jsfiddle/wUAGP/440/
$(document).ready(function(){
var $moveable = $('.moveAble');
$(document).mousemove(function(e){
$moveable.css({'top': e.pageY,'left': e.pageX});
});
});
Thanks to @nnnnnn for mentioning the caching of $moveable
$(document).ready(function(){
$('div.moveAble').mousemove(function(e){
var y = e.pageY;
var x = e.pageX;
$('.moveAble').css('top', y-20).css('left', x-20);
});
});
Look this $('.moveAble').css('top', y-20).css('left', x-20);
Your mouse is just at border, so you need to shift it.
fiddle : http://jsfiddle/wUAGP/436/