Hi all I have a class called “squareOne” that contains a hidden square and reveals itself when the window.scrollY is at 20. After this occurs I want “sqaureOne” to hide itself again at window.scrollY 30 and reveal a second class called “squareTwo”. As you can see in my JavaScript I tried adding another if statement but my syntax is most likely wrong. Can anyone help? Thanks in advance.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>show/hide</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div parent>
<div id="s1" class="squareOne hide"></div>
<div id="s2" class="squareTwo hide"></div>
</div>
<script src="script.js"></script>
</body>
</html>
body {
height: 2000px;
}
.parent{
width: 100vw;
height: 100vh;
display: grid;
place-items: center;
}
.squareOne {
position: fixed;
width: 60px;
height: 60px;
background: palegreen;
z-index: 1;
transition: all .5s;
}
.squareTwo{
position: fixed;
width: 60px;
height: 60px;
background: orange;
z-index: 1;
transition: all .5s;
}
.hide {
opacity:0;
}
.show {
opacity:1;
}
s1 = document.getElementById("s1");
s2 = document.getElementById("s2");
var myScrollFunc = function () {
var y = window.scrollY;
if (y >= 20) {
s1.className = "squareOne show"
}
//This part is the main issue.//
if (y >= 30) {
s1.className = "squareOne hide"
}
if (y >= 40) {
s2.className = "squareTwo show"
} if (y >= 50) {
s2.className = "squareTwo hide"
}
};
window.addEventListener("scroll", myScrollFunc);
3
Answers
The problem with your code is that you’re using multiple if statements that can override each other. For instance, when you scroll to scrollY = 31, the first if condition (y >= 20) is still true, so it will continue to apply the "show" class to the squareOne. Immediately after, (y >= 30) is also true, which hides it again. This causes flickering and unexpected behavior.
To fix the issue, you should use a series of if-else statements, and also consider ranges for showing and hiding each element. Here’s how to fix it:
Here’s a brief breakdown of what the code does:
This will prevent the flickering and unexpected behavior by ensuring only one condition is met at a time.
I have edited your scroll function:
I have used bigger values than 20 and 30 to make it more visible. You can change these. The important thing is to have a range for the first box as it should appear between 20 and 30 y-value and hide before box 2 appears at 30. Otherwise before 20 they should both be hidden and above 30 only box 2 should be showing.
Hope this helps.
Update from comment
You need to add another condition statement
Do your logic from the opposite side.