As a newcomer to JQuery, I decided to experiment with creating a parallax background effect using the mousemove function. By utilizing event.pageX
to generate a variable for adjusting the background position, I was able to achieve the desired result.
Although my code is quite basic, it gets the job done. However, I have noticed that upon refreshing the page, the parallax effect only begins after moving the mouse. Ideally, I would like the effect to start automatically when the page loads instead of requiring initial user interaction.
Is there a way to trigger the mousemove
function automatically on page load? Or perhaps there's a more efficient approach to structuring the code for this task?
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%;
}