Reputation: 615
I have an html
with body
's height
and width
properties set to 100%
, and a large viewport
div
for scrolling.
I want to catch the event in both desktop and mobile browsers.
But now, it's not working, when the viewport
div
is scrolling.
;
(function() {
var viewport = document.getElementById('viewport');
function test() {
console.log("aaa");
}
viewport.addEventListener('scroll', test, false);
//nothing happen here
window.addEventListener('resize', function() {
}, false);
})();
#box {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
#viewport {
width: 12222px;
height: 5000px;
position: relative;
top: 0;
left: 0;
background-color: gray;
background-image: repeating-linear-gradient(45deg, transparent, transparent 35px, rgba(255, 255, 255, .5) 35px, rgba(255, 255, 255, .5) 70px);
}
html,
body {
padding: 0;
margin: 0;
width: 100%;
height: 100%;
overflow: scroll;
}
#info {
position: fixed;
top: 30%;
font-size: 2em;
z-index: 1;
width: 100%;
text-align: center;
color: #fff;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
</head>
<body>
<p id="info">text</p>
<div id="viewport">
<div id="box"></div>
</div>
</body>
</html>
How can I get this to work?
Upvotes: 0
Views: 10864
Reputation: 616
The scroll event always gets fired on the body element until you set the body non-scrollable with style:"overflow: hidden". Then make a div or section of the page scrollable. For reference use this link which explains all the details: Prevent body scrolling but allow overlay scrolling
Upvotes: 1
Reputation: 2378
It is not working because scroll
event fired on body, not on your '.viewport' element. Try
;
(function() {
var viewport = document.getElementsByTagName('body')[0];
function test() {
console.log("aaa");
}
viewport.addEventListener('scroll', test, false);
//nothing happen here
window.addEventListener('resize', function() {
}, false);
})();
Upvotes: 0