11223342124 11223342124 - 1 month ago 8
jQuery Question

Why onscroll function doesn't work?

I am making div element that should fade in/out on scroll. I tried simply alerting on scroll(without fading) with onscroll, scroll, DOMMouseScroll, mousewheel, also with jquery, but it doesn't work with any of these. Only works with onmousewheel in Chrome.

https://jsfiddle.net/643v7rod/

var el = document.getElementById('el');

var opacity = 1;
el.onmousewheel = function(e){
if(e.deltaY > 0){
opacity -= 0.25;
el.style.opacity = opacity;
}else{
opacity += 0.25;
el.style.opacity = opacity;
}
}


What am I doing wrong here?

Answer

That mouse event has been deprecated, see this

Try this one instead, and make sure your div's height is enough so that you can scroll :)

var el = document.getElementById('el');
var opacity = 1;
//if you want to be able to revert the effect, you will
//have to store the current window position 
//in a variable and update it each time;
var position = window.scrollY;
//declaring the function
function effect(){
	if(window.scrollY > position){
		opacity -= 0.01;
		el.style.opacity = opacity;
        //now update the positoin
        position = window.scrollY;
	}else{
		opacity += 0.01;
		el.style.opacity = opacity;
        //do it again
        position = window.scrollY;
	}
};
//adding the event listener
window.addEventListener("scroll", effect);
#el {
	width: 300px;
	height: 1200px;
	background-color: red;
}
<div id="el"></div>

I have changed the opacity rate so that you get a clear visual of the effect.

Comments