making my own Jquery parallax effect
-
29-10-2019 - |
Question
I'm making a jquery parallax effect where when the user first hovers the mouse over the document, the foreground layer will move towards the mouse cursor such that the mouse cursor will be over the center of the foreground layer. Afterwards, when the user moves around the mouse cursor, the foreground layer should move the opposite direction of the mouse cursor; the background layer will also move in the opposite direction but slower to produce the parallax effect.
The problem is that after the foreground layer moves toward the mouse cursor using the mouseover
event and I trigger the mousemove
event, the foreground and background layers will "jump" to another location.
Solution
I have updated your example and it seems, that it works ok now (at least in Google Chrome 15 and IE9).
Basically, I have changed mouseover
to mouseenter
and made the coordinates calculation in mouseenter
same as in mousemove
.
UPDATE:
In addition I have removed the use of a variable and I'm just unsubscribing from the mousemove
event (jQuery.unbind
), while the mouseenter
handler is running.
Here is the code for reference:
function onmousemovehandler(e){
mouse_dx = -(e.pageX);
mouse_dy = -(e.pageY);
$('#foreg').css({
'left': mouse_dx,
'top': mouse_dy
});
mouse_dx = (mouse_dx) / 2;
mouse_dy = (mouse_dy) / 2;
$('#backg').css({
'left': mouse_dx,
'top': mouse_dy
});
};
$(document).mouseenter(function(e) {
$(document).unbind('mousemove', onmousemovehandler);
mouse_x = -(e.pageX);
mouse_y = -(e.pageY);
$('#foreg').animate({
'left': mouse_x,
'top': mouse_y
},
300);
$('#backg').animate({
'left': mouse_x/2,
'top': mouse_y/2
},
300,
function() {
$(document).mousemove(onmousemovehandler);
});
});