[Solved] Why isn’t my image doing a parallax scroll?


You do get your scrolltop in the console like that, on codepen, but likely not on local.

Learn about

$(document).ready(function(){

Always load the jQuery src first, after the body element, then the rest of the JS code. Or inline it after the body closing tag. But always the jQuery first.

Then , depending on the functionility, you might need the doc ready wrapper, here, you need it.

Next, you need a reference element, if you only have one element on the page, there can be no parallax. I have added a h1 for demo purposes.

Your full function:

$(document).ready(function(){   //wait until the DOM is loaded
var wdw = $(window);   // cache the DOM object, always cache esp with jQuery
var header = $('.header-bg');
var hOne= $('h1');
wdw.scroll(function() {   // scroll listener on window
var scrollTop = $(this).scrollTop();
header.css('top',-(scrollTop * 0.8) + 'px');
hOne.css('top',+(scrollTop * 0.8) + 'px');
if(hOne.scrollTop() <= 10){
hOne.css('opacity', '0.4');
}
else {
hOne.css('opacity', '1');
}
console.log(scrollTop);
});

});

Here is the link

https://codepen.io/damianocel/pen/zdzQYe

Note that this kind of stuff needs scroll throttling, there are 2 new APIs for this kind of things, this code is not perfect, but it runs and at least I have cached the variables.

Now, I think this is very simple in plain JS, if you knew how to do this in plain JS, this question would not exist. Seriously, loading a jQuery for a parallax functionality is like punching babies,lol.

solved Why isn’t my image doing a parallax scroll?