I am trying to change the background image when the user scrolls the page. The code I have written is not working. I am running this code on a WordPress website. Below Is my code.
<script type="text/javascript">
jQuery(document).ready(function( jQuery ) {
jQuery(window).on('scroll touchmove', function() {
if (jQuery(document).scrollTop() >= jQuery('#one').position().top) {
jQuery('body').css('background', jQuery('#one').attr('data-src'));
}
if (jQuery(document).scrollTop() > jQuery('#two').position().top) {
jQuery('body').css('background', jQuery('#two').attr('data-src'));
}
if (jQuery(document).scrollTop() > jQuery('#three').position().top) {
jQuery('body').css('background', jQuery('#three').attr('data-src'));
}
if (jQuery(document).scrollTop() > jQuery('#four').position().top) {
jQuery('body').css('background', jQuery('#four').attr('data-src'));
}
if (jQuery(document).scrollTop() > jQuery('#five').position().top) {
jQuery('body').css('background', jQuery('#five').attr('data-src'));
}
});
})(jQuery);
</script>
Here I have five sections and I gave an ID to my section as I define on the code. Below is how I added the 'data-src' attribute to the particular section through the elementor data attribute option.
data-src|http://www.kasundev.xyz/design/wp-content/uploads/2022/02/WhatsApp-Image-2022-02-10-at-11.00.38.jpeg
This is the CSS I am using when the page loads first. This code applies to the whole page.
body {
background:#333333;
transition: all 1200ms ease-out;
will-change: background;
}
My question is nothing is changing when I scroll. Instead of an image If I give a color like this data-color|#000000 will change.
How I change my background image when scrolling. Can anyone help me out?
Thanks
CodePudding user response:
You need to add url('image path') around the image.