I am still a beginner with JQuery and I took it upon myself to figure out a parallax background (I believe this is referred to as a parallax effect) using mousemove. I am using event.pageX
to create a variable that is later used in setting the background position.
It works but the code is defiantly novice level. Every time I refresh the page I need to move the mouse for the background to start the parallax effect - so, for example, the background starts with at 50% 0% and when I move the mouse it goes to 10.5% 0% and is smooth after that first initial mouse movement.
I was wondering if there was a way to automatically call the mousemove
function on page load. Or is there a better way to reformat the code for what I am trying to do?
JS
$('.background').on( "mousemove", function( event ) {
var Xparallax = (event.pageX / 300)
$('.background').css({
'background-position' : Xparallax + '% 15%'
});
});
HTML
<div class="background" style=""></div>
CSS
div.background {
position: absolute;
width: 100%;
height: 100%;
left: 0px;
top: 0px;
background-image: url("/images/bg3.jpg");
background-position: 50% 15%;
background-size: 125%;
}
Try this one :