Hi i tried to make the div smaller wqhen scrolling. however i found some article that the div is small then when scroll it make bigger. i wanted the opposite. when run the image is 100% then when scroll it will be smaller. can someone help me please? i am new to this
This is the code:
https://codesandbox.io/s/sharp-lewin-to1o2b?file=/index.html
Html:
JavaScript
x
41
41
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8" />
5
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
7
<title>Static Template</title>
8
</head>
9
<body>
10
<div id="animatedDiv"></div>
11
</body>
12
</html>
13
<style>
14
#animatedDiv {
15
background: #dc143c;
16
min-height: 9000px;
17
min-width: 20%;
18
position: absolute;
19
}
20
</style>
21
22
<script>
23
var aDiv = document.getElementById("animatedDiv");
24
25
function changeWidth() {
26
var scrollVal = window.pageYOffset;
27
var scrollSlow = scrollVal / 4;
28
29
//Changing CSS Width
30
aDiv.style.width = Math.min(Math.max(scrollSlow, 20), 100) + "%";
31
}
32
33
window.addEventListener(
34
"scroll",
35
function () {
36
requestAnimationFrame(changeWidth);
37
},
38
false
39
);
40
</script>
41
Advertisement
Answer
I did it with my math logic
JavaScript
1
44
44
1
<!DOCTYPE html>
2
<html lang="en">
3
<head>
4
<meta charset="UTF-8" />
5
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
7
<title>Static Template</title>
8
</head>
9
<body>
10
<div id="animatedDiv"></div>
11
</body>
12
</html>
13
<style>
14
#animatedDiv {
15
background: #dc143c;
16
min-height: 9000px;
17
width: 100%;
18
position: absolute;
19
}
20
</style>
21
22
<script>
23
var aDiv = document.getElementById("animatedDiv");
24
25
function changeWidth() {
26
var scrollVal = window.pageYOffset;
27
28
//Changing CSS Width
29
30
/* This lags if you scroll fast.. aDiv.style.width = (100 - (scrollVal*100/800)) + "%";
31
I just tried it out, so instead use the code down above, 800 to 1500 doesn't matter, I just increased time of animation
32
*/
33
//NOTE this line checks if PERCENT <= 10 then sets width to 10%
34
( (100 - (scrollVal*100/1500)) ) <= 10 ? aDiv.style.width = "10%" : aDiv.style.width = (100 - (scrollVal*100/1500)) + "%";
35
}
36
37
window.addEventListener(
38
"scroll",
39
function () {
40
requestAnimationFrame(changeWidth);
41
},
42
false
43
);
44
</script>