I am practicing Javascript and css. I want to change my background color when scrolling down. I don't want to use library for that. I have followed this code-pen demo to learn the logic but he used jquery. I have followed w3school for scrollTop .My javascript logic works but it does not work like this demo. I think I have to target each div in order to change the background-color but don't know how.
function showScrollColorChange() {
//let scroll = window.scrollTop() + (window.height() / 3);
if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 30) {
document.body.classList.add('color-violet')
} if (document.body.scrollTop > 40 || document.documentElement.scrollTop > 40) {
document.body.classList.add('color-green')
} else {
document.body.classList.add('color-orange')
}
}
/* document.body.addEventListener('scroll', () => {
showScrollColorChange()
}) */
window.onscroll = function () { showScrollColorChange() };
*{
box-sizing: border-box;
}
body{
margin: 0;
padding: 0;
transition: background 300ms linear, color 300ms linear;
}
.container{
display: flex;
justify-content: center;
margin-top: 20px;
padding: 50px;
min-height: 100vh;
}
p{
width:50%;
font-size: 20px;
}
img {
width:500px;
height: 500px;
border-radius: 5px;
}
/* colours */
.color-violet {
background-color: #7A4EAB;
}
.color-indigo {
background-color: #4332CF;
}
.color-blue {
background-color: #2F8FED;
}
.color-green {
background-color: #4DCF42;
}
.color-yellow {
background-color: #FAEB33;
}
.color-orange {
background-color: #F19031;
}
.color-red {
background-color: #F2293A;
}
<div class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
Here is a dynamic way.
Get all containers elements and add the position of their top to an array:
containers = document.getElementsByClassName("container");
var containertops = [];
containertops.push(0); // add for space before 1st container
for (var i = 0; i < containers.length; i++) {
containertops.push(containers[i].offsetTop);
}
Make an array of the colour classes in the order to be used. It is easy to change the colours and order doing this:
// array of colours to use
var colours = [
"white",
"color-violet",
"color-indigo",
"color-blue",
"color-green",
"color-yellow",
"color-orange",
"color-red",
];
In scroll function, loop through the array of containers top positions. For each i in the loop, use this as an index to get a new colour from the colours array so the colour changes for every container. If there are more containers than colours, use the last colour for the rest.
// loop through the containers and add a new colour as the containers change
for (var i = 0; i < containertops.length; i++) {
// if this container is at the top of the screen get a new colour class
if (document.body.scrollTop >= containertops[i] || document.documentElement.scrollTop >= containertops[i]) {
document.body.className = ''; // clear class
// if we have not enough colours, use the last colour class again
colourclass= (i>=colours.length?colours.length-1: i);
document.body.classList.add(colours[colourclass]);
}
}
This is the code working:
//dynamically add all containers to array
containers = document.getElementsByClassName("container");
var containertops = [];
containertops.push(0); // add for space before 1st container
for (var i = 0; i < containers.length; i++) {
containertops.push(containers[i].offsetTop);
}
// array of colours to use
var colours = [
"white",
"color-violet",
"color-indigo",
"color-blue",
"color-green",
"color-yellow",
"color-orange",
"color-red",
];
function showScrollColorChange() {
// loop through the containers and add a new colour as the containers change
for (var i = 0; i < containertops.length; i++) {
// if this container is at the top of the screen get a new colour class
if (document.body.scrollTop >= containertops[i] || document.documentElement.scrollTop >= containertops[i]) {
document.body.className = ''; // clear class
// if we have not enough colours, use the last colour class again
colourclass= (i>=colours.length?colours.length-1: i);
document.body.classList.add(colours[colourclass]);
}
}
}
window.onscroll = function() {
showScrollColorChange()
};
* {
box-sizing: border-box;
}
body {
margin: 0;
padding: 0;
transition: background 300ms linear, color 300ms linear;
}
.container {
display: flex;
justify-content: center;
margin-top: 20px;
padding: 50px;
min-height: 100vh;
}
p {
width: 50%;
font-size: 20px;
}
img {
width: 500px;
height: 500px;
border-radius: 5px;
}
/* colours */
.color-violet {
background-color: #7A4EAB;
}
.color-indigo {
background-color: #4332CF;
}
.color-blue {
background-color: #2F8FED;
}
.color-green {
background-color: #4DCF42;
}
.color-yellow {
background-color: #FAEB33;
}
.color-orange {
background-color: #F19031;
}
.color-red {
background-color: #F2293A;
}
<div class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
I see 2 solutions:
You only add classes to your body, so with time body will have every class and its color will be set to last class added, so you should also remove each unused class with classList.remove('className');
Just change body background with document.body.style.background = '#FFFFFF', and add comments for each color changed to avoid confusion.
IntersectionObserver comes here very handy. You just observer every container.
I have put an custom attribute called _class to the element. It holds the name of the class that should be added / removed if the elemen enters / leaves the viewport.
The observer runs off the main thread so its more performant.
To see how it works you need to turn on fullscreen. The threshold is set to 0.9 witch means 90% of the div needs to be visible before the class will be added to the body.
let containers = document.querySelectorAll(".container")
let observer = new IntersectionObserver((entries) => {
entries.forEach((entry, i) => {
let color = entry.target.attributes._class.nodeValue;
if(entry.isIntersecting) {
document.body.className = "";
document.body.classList.add(color);
}
})
}, {threshold: 0.9})
containers.forEach(container => {
observer.observe(container);
})
*{
box-sizing: border-box;
padding: 0;
margin: 0;
}
body{
margin: 0;
padding: 0;
transition: background 300ms linear, color 300ms linear;
}
.container{
display: flex;
justify-content: center;
margin-top: 20px;
padding: 50px;
min-height: 100vh;
}
p{
width:50%;
font-size: 20px;
}
img {
width:500px;
height: 500px;
border-radius: 5px;
}
/* colours */
.color-violet {
background-color: #7A4EAB;
}
.color-indigo {
background-color: #4332CF;
}
.color-blue {
background-color: #2F8FED;
}
.color-green {
background-color: #4DCF42;
}
.color-yellow {
background-color: #FAEB33;
}
.color-orange {
background-color: #F19031;
}
.color-red {
background-color: #F2293A;
}
<div _class="color-violet" class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div _class="color-indigo" class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div _class="color-blue" class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div _class="color-green" class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
<div _class="color-yellow" class="container">
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Nihil at eaque in aliquam assumenda. Officiis omnis ex
sunt quaerat magni. Provident at nihil molestias dolores tempora voluptas laborum aspernatur sint.</p>
<img src="https://images.unsplash.com/photo-1599736375341-51b0a848f3c7?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=800&q=60" alt="">
</div>
Related
In the images below, the small box is like a tab, when clicked it will show the content at the bottom of it.
When the window / viewed in a smaller screen it will reduce the columns accordingly, however it should preserve its functionality.
Tablet
Mobile
const about = document.querySelector(".wrapper");
const btns = document.querySelectorAll(".accordion");
const articles = document.querySelectorAll(".content");
about.addEventListener("click", function(e) {
const id = e.target.dataset.id;
if (id) {
// remove selected from other buttons
btns.forEach(function(btn) {
btn.classList.remove("active");
});
e.target.classList.add("active");
// hide other articles
articles.forEach(function(article) {
article.classList.remove("active");
});
const element = document.getElementById(id);
element.classList.add("active");
}
});
* {
margin: 0 auto;
padding: 0;
max-width: 1000px;
box-sizing: border-box;
background-color: gray;
}
.accordion {
margin-top: 5px;
background-color: #eee;
color: #444;
padding: 15px;
width: 50%;
transition: 0.4s;
}
.accordion.active {
background-color: #ccc;
}
.post-container {
content: "";
display: table;
clear: both;
}
.container {
display: flex;
flex-direction: row;
gap: 6px;
}
.wrapper {
display: flex;
flex-direction: column;
}
.content {
display: none;
}
.wrapper2 {
width: 100%;
}
.content.active {
display: block;
padding: 20px;
}
.active,
.accordion:hover {
background-color: #ccc;
}
<main class="wrapper">
<section class="wrapper2">
<div class="container">
<button data-id="1" class="accordion">Section 1</button>
<button data-id="2" class="accordion">Section 2</button>
<button data-id="3" class="accordion">Section 3</button>
</div>
<div id="1" class="content">Lorem ipsum dolor sit amet consectetur adipisicing elit. Iure ipsa optio eaque placeat aut deleniti facere nisi repudiandae sequi distinctio? Error dignissimos excepturi perferendis pariatur ad a ratione dolore atque.</div>
<div id="2" class="content">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Assumenda nesciunt autem dignissimos commodi ut velit iure sequi eveniet repudiandae. Nisi impedit ad, libero voluptates autem minima corporis mollitia illo eum.</div>
<div id="3" class="content">Lorem ipsum dolor sit amet consectetur adipisicing elit. Doloribus, numquam culpa. Impedit voluptates ad ea distinctio a doloremque ex officiis ducimus, nobis nihil qui repudiandae, dolore, pariatur ratione error nemo.</div>
</section>
<section class="wrapper2">
<div class="container">
<button data-id="4" class="accordion">Section 4</button>
<button data-id="5" class="accordion">Section 5</button>
<button data-id="6" class="accordion">Section 6</button>
</div>
<div id="4" class="content">Lorem, ipsum dolor sit amet consectetur adipisicing elit. Dolor ducimus cupiditate fuga ratione tempore eveniet possimus maiores quod sequi natus? Iusto dolor hic facilis culpa ad illo vel deserunt minima?</div>
<div id="5" class="content">Lorem ipsum dolor sit amet consectetur adipisicing elit. Tenetur nihil obcaecati a cumque quos adipisci aliquam illum perspiciatis fugit, tempora aperiam officiis dignissimos odit incidunt modi tempore corporis. Porro, a.</div>
<div id="6" class="content">Lorem ipsum dolor sit amet consectetur adipisicing elit. Dolorum, quis est. Animi fuga ipsum porro ullam blanditiis illum inventore magnam, earum nesciunt ab quis placeat iste quo! Repudiandae, ratione sapiente!</div>
</section>
</main>
I spent the weekend trying to get my head around the Intersection Observer Animation for an animation that I'm trying to achieve. From my understanding of the intersection observer my code should work as I intended but the reality is it doesn't 🥲
My goal is that the scroll animation starts when the element reaches a certain point within the viewport. In my codepen, I've marked the point where the animation should start with a border. However, the animation starts as soon as the div enters the viewport.
Also, when the element gets below the border again, the animation should stop.
I would very much appreciate any help to achieve my goal.
Code example: https://codepen.io/aki-sol/pen/RwJPJrW?editors=1111
Also, if you have any feedback on my animation approach I'm very happy to receive criticism/ better way of approaching this.
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
<div class="box">
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
</div>
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
body {
position: relatvie;
heig;
}
body:after {
content: '';
position: fixed;
bottom: 40%;
height: 1px;
width: 100%;
border-bottom: 1px solid blue;
}
.text {
background-color: brown;
color: white;
height: 150vh;
}
.box {
display: flex;
position: relative;
}
.box-content {
width: 200px;
height: 200px;
background-color: greenyellow;
margin-right: 50px;
}
const boxElement = document.querySelector(".box");
//this function calls the aniamtion function and observes the window scroll position
function getWindowScrollPos() {
let windowPosition = window.scrollY;
window.addEventListener("scroll", () => {
windowPosition = window.scrollY;
animateBox(boxElement, windowPosition);
});
}
function animateBox(box, scrollPosition) {
let boxOffsetPosition = scrollPosition;
box.style.left = `${-boxOffsetPosition}px `;
}
function boxObserver(element) {
const observer = new IntersectionObserver(
(entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
getWindowScrollPos();
}
});
},
{ rootMargin: "0% 0% 60% 0%" }
);
observer.observe(element);
}
boxObserver(boxElement);
Thanks a lot!
There are two things to note here, I guess.
First, the Intersection Observer (along with Resize Observer) is not the best thing to test in online sandboxes, because they run code in an iframe, which leads to such a behavior. You should try to run your code in a browser.
There are questions related to this problem. E.g.: In codepen, Intersection observer has different behavior from browser window
Second, you're probably misunderstanding rootMargin. You set it to 0% 0% 60% 0% which means “add 60% of the height of the root to the very root, and use it as a bottom border for intersection”.
What you actually want to is to decrease the bottom border, not to increase. So, just set it to 0% 0% -40% 0% and it will work.
The Intersection Observer tutorial that helped me a bit to understand the rootMargin weirdness. Maybe it will be useful for you too.
Demo
Here's your snippet that I changed a bit to make it work inside an iframe. I've added a container node and use it instead of window.
const boxElement = document.querySelector('.box');
const container = document.getElementById('container');
function setupListener() {
let scrollPosition = container.scrollTop;
animateBox(boxElement, scrollPosition);
container.addEventListener('scroll', () => {
scrollPosition = container.scrollTop;
animateBox(boxElement, scrollPosition);
});
}
function animateBox(box, scrollPosition) {
let boxOffsetPosition = scrollPosition;
box.style.left = `${-boxOffsetPosition}px`;
}
function boxObserver(element) {
const observer = new IntersectionObserver(
(entries, observer) => {
entries.forEach((entry) => {
if (entry.isIntersecting) {
setupListener();
}
});
},
{
root: document.getElementById('container'),
rootMargin: `0px 0px -40% 0px`
}
);
observer.observe(element);
}
boxObserver(boxElement);
body {
margin: 0;
overflow: hidden;
}
body:after {
content: "";
position: fixed;
bottom: 40%;
height: 1px;
width: 100%;
border-bottom: 1px solid blue;
}
.container {
overflow: scroll;
max-height: 100vh;
}
.text {
background-color: brown;
color: white;
height: 150vh;
}
.box {
display: flex;
position: relative;
}
.box-content {
width: 200px;
height: 200px;
background-color: greenyellow;
margin-right: 50px;
}
<div class="container" id="container">
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
<div class="box">
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
<div class="box-content"></div>
</div>
<div class="text">
Lorem ipsum, dolor sit amet consectetur adipisicing elit. Expedita provident unde, sequi aliquid porro ipsa vitae nulla dolor neque aliquam quisquam nam magnam architecto, consequuntur est in beatae, nihil optio.
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Et, architecto eveniet assumenda praesentium in laboriosam vitae atque, sunt minima aliquid quam distinctio voluptatum commodi veniam iure officia provident voluptas ea?
Lorem ipsum dolor sit amet consectetur adipisicing elit. Eveniet quo commodi laborum perspiciatis nemo voluptates quod odio quis necessitatibus perferendis? Ipsum, quasi nesciunt. Debitis omnis consequuntur laboriosam veniam, non impedit!
</div>
</div>
What may be improved
Also, if you have any feedback on my animation approach I'm very happy to receive criticism/ better way of approaching this.
Well, you surely should think about the scroll listener you will have after the intersection started. If you don't remove it, it will hang. Or even worse, they will be increasing during each intersection. Not a good thing.
Also it's better to animate transform, not left. It's good for optimization. Otherwise you'll get junky animation which will freeze the whole site. Check this set of articles by Google: web.dev/animations/.
I am new to coding and I am trying to achieve the following using JQuery:
I have two Divs Where clicking on the first shows some content and clicking the second would hide the content of the first one and show its content instead (Toggling). What I want to do is that I want to keep the same functionality but I want the second Div to slide to the right when I click on the first Div and make a drawer shape and vice versa. I have attached images to it so it may explain more about my idea.
both of contents are hidden by default.
I can't seem to know how to join these two functionalities together
HTML
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Test</title>
<script
src="https://code.jquery.com/jquery-3.5.1.js"
integrity="sha256-QWo7LDvxbWT2tbbQ97B53yJnYU3WhH/C8ycbRAkjPDc="
crossorigin="anonymous"
></script>
<link rel="stylesheet" href="style.css" />
<script src="script.js"></script>
</head>
<body>
<div id="box-container">
<div id="div1">
<h1>Title one</h1>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Inventore
quidem ex tenetur ipsum dolore repudiandae molestiae mollitia! Dolore
numquam.
</p>
</div>
<div id="div2">
<h1>Title two</h1>
<p>
Lorem ipsum dolor sit amet consectetur, adipisicing elit. Inventore
quidem ex tenetur ipsum dolore repudiandae molestiae mollitia! Dolore
numquam.
</p>
</div>
</div>
<div id="contentDiv1">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla voluptatem
veritatis assumenda. Obcaecati veniam quo impedit tempora pariatur maiores
ipsa voluptates commodi esse eveniet! Nihil corrupti illum at accusantium
sit? Lorem ipsum dolor sit amet consectetur adipisicing elit. Ut veritatis
et molestias? Reprehenderit distinctio sint provident ratione dolorem
veritatis sapiente, fuga amet obcaecati. Laboriosam rerum consectetur nemo
magnam saepe mollitia. Lorem ipsum dolor sit amet consectetur adipisicing
elit. Excepturi sit perferendis earum debitis corrupti dolore commodi
minima consectetur veniam itaque inventore et pariatur sapiente, maxime
quis, in nulla, eos molestias! Lorem ipsum dolor sit amet consectetur,
adipisicing elit. Quasi, incidunt repudiandae perferendis ea praesentium
blanditiis, voluptate accusantium, repellat molestiae quisquam eveniet
earum officia sed assumenda maxime officiis sequi laboriosam! Tempore.
Lorem ipsum dolor sit amet consectetur adipisicing elit. Alias modi hic
officia iste optio in delectus veniam obcaecati reprehenderit, voluptate
ipsum! Incidunt ducimus animi, id quae blanditiis provident dignissimos
harum?
</div>
<div id="contentDiv2">
Lorem ipsum dolor sit amet consectetur adipisicing elit. Nulla voluptatem
veritatis assumenda. Obcaecati veniam quo impedit tempora pariatur maiores
ipsa voluptates commodi esse eveniet! Nihil corrupti illum at accusantium
sit? Lorem ipsum dolor sit amet consectetur adipisicing elit. Ut veritatis
et molestias? Reprehenderit distinctio sint provident ratione dolorem
veritatis sapiente, fuga amet obcaecati. Laboriosam rerum consectetur nemo
magnam saepe mollitia. Lorem ipsum dolor sit amet consectetur adipisicing
elit. Excepturi sit perferendis earum debitis corrupti dolore commodi
minima consectetur veniam itaque inventore et pariatur sapiente, maxime
quis, in nulla, eos molestias! Lorem ipsum dolor sit amet consectetur,
adipisicing elit. Quasi, incidunt repudiandae perferendis ea praesentium
blanditiis, voluptate accusantium, repellat molestiae quisquam eveniet
earum officia sed assumenda maxime officiis sequi laboriosam! Tempore.
Lorem ipsum dolor sit amet consectetur adipisicing elit. Alias modi hic
officia iste optio in delectus veniam obcaecati reprehenderit, voluptate
ipsum! Incidunt ducimus animi, id quae blanditiis provident dignissimos
harum?
</div>
</body>
</html>
CSS
body {
display: inline-block;
margin: 100px 100px 25px 100px;
text-align: center;
}
#box-container {
height: 300px;
display: flex;
}
#div1 {
background: linear-gradient(90deg, #f57350, #fa8282);
width: 50%;
height: 50%;
cursor: pointer;
}
#div2 {
background: linear-gradient(90deg, #a42e5a, #f57350);
width: 50%;
height: 50%;
cursor: pointer;
}
#contentDiv1,
#contetnDiv2 {
margin: 25px;
}
JQuery
jQuery(document).ready(function($){
$('#contentDiv1').hide();
$('#contentDiv2').hide();
$('#div1').on('click', function(){
$('#contentDiv1').slideToggle();
$('#contentDiv2').hide();
});
$('#div2').on('click', function(){
$('#contentDiv2').slideToggle();
$('#contentDiv1').hide();
});
});
attached image
It has more than one solution, and for me, this is my favorite method, I hope it helps you:
$('.tabs .tab').on('click', function () {
if ($(this).hasClass('active')) {
$(this).removeClass('active')
.closest('.tabs').removeClass('active1 active2');
$('.content').hide();
} else {
let i = $(this).index() + 1;
$(this)
.addClass('active')
.siblings('.tab').removeClass('active')
.closest('.tabs').removeClass('active1 active2')
.addClass('active' + i);
$('.content').hide();
$('.content' + i).fadeIn();
}
});
.tabs,
.tabs .tab,
.tabs .content {
border: 1px solid #000;
border-collapse: collapse;
box-sizing: border-box;
}
.tabs {
display: flex;
flex-wrap: wrap;
text-align: center;
position: relative;
}
.tabs.active1 {
padding-left: 0;
padding-right: 65px;
}
.tabs.active2 {
padding-left: 65px;
padding-right: 0;
}
.tabs .tab {
padding: 15px;
cursor: pointer;
min-width: 50%;
display: flex;
justify-content: center;
align-items: center;
}
.tabs.active1 .tab,
.tabs.active2 .tab {
min-width: 100%;
width: 100%;
}
.tabs .content {
padding: 15px;
min-width: 100%;
display: none;
}
.tabs.active1 .tab1:not(.active),
.tabs.active2 .tab1:not(.active){
position: absolute;
left: 0;
top: 0;
bottom: 0;
min-width: 65px;
width: 65px;
}
.tabs.active1 .tab2:not(.active),
.tabs.active2 .tab2:not(.active) {
position: absolute;
right: 0;
top: 0;
bottom: 0;
min-width: 65px;
width: 65px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="tabs">
<div class="tab tab1">div1</div>
<div class="tab tab2">div2</div>
<div class="content content1">div content1</div>
<div class="content content2">div content2</div>
</div>
I am experimenting with a very basic layout that has 4 divs, the first and third divs have dark blue backgrounds and the second and fourth have white backgrounds. I have a div in fixed position to the right with a default white color. I need to write some code that if this fixed div is scrolled through the white background divs, it changes its color to black, if it scrolled in the blue, it remains white as it is.
I tinkered for a whole day with getClientBoundingRect() and the IntersectionObserver API and I didn't have any luck.
Here is the code of the basic layout:
const oddElems = document.querySelectorAll('.oddElem');
const evenElems = document.querySelectorAll('.evenElem');
const allElems = document.querySelectorAll('.elem');
function handleInteresection(entries) {
entries.forEach(entry => {
console.log(entry)
})
}
const observer = new IntersectionObserver(handleInteresection);
allElems.forEach(elem => {
observer.observe(elem);
})
* {
box-sizing: border-box;
}
body {
width: 70%;
margin: auto;
padding: 0;
}
.elem {
border: 2px solid;
}
#elem {
background: #007;
padding: 20rem;
color: white;
}
#elem2 {
padding: 20rem;
background: #fff;
}
#elem3 {
padding: 20rem;
background: #007;
}
#elem4 {
padding: 20rem;
background: #fff;
}
#flyingbox {
padding: 2rem;
width: 2rem;
left: 80%;
position: fixed;
top: 10px;
background: #fff;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Bounding</title>
</head>
<body>
<div id="flyingbox">
</div>
<div class="elem oddElem" id="elem">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa blanditiis reprehenderit odio, eos
recusandae ipsam nulla quas sed voluptatum ex neque natus fuga illum dolores. Quis quibusdam odit, unde
minus?
</p>
</div>
<div class="elem evenElem" id="elem2">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa blanditiis reprehenderit odio, eos
recusandae ipsam nulla quas sed voluptatum ex neque natus fuga illum dolores. Quis quibusdam odit, unde
minus?
</p>
</div>
<div class="elem oddElem" id="elem3">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa blanditiis reprehenderit odio, eos
recusandae ipsam nulla quas sed voluptatum ex neque natus fuga illum dolores. Quis quibusdam odit, unde
minus?
</p>
</div>
<div class="elem evenElem" id="elem4">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa blanditiis reprehenderit odio, eos
recusandae ipsam nulla quas sed voluptatum ex neque natus fuga illum dolores. Quis quibusdam odit, unde
minus?
</p>
</div>
</body>
</html>
It doesn't look like you have any event listener to track the current scroll position. Basically I created an array of each section's offsetTop (distance from parent top) in reverse order, and conditionally check whether window.scrollY (current scroll position) matches an even or odd index.
const allElems = document.querySelectorAll('.elem');
const offsetTops = Array.from(allElems).map(ele => ele.offsetTop).reverse();
const flyingBox = document.getElementById("flyingbox");
window.addEventListener("scroll", ()=> {
const isBlack = offsetTops.findIndex(offsetTop => window.scrollY + 45 > offsetTop)%2 === 0 ? true : false;
if(flyingBox.classList.contains("black") && !isBlack) flyingBox.classList.toggle("black");
if(!flyingBox.classList.contains("black") && isBlack) flyingBox.classList.toggle("black");
});
* {
box-sizing: border-box;
}
body {
width: 70%;
margin: auto;
padding: 0;
}
.elem {
border: 2px solid;
}
#elem {
background: #007;
padding: 20rem;
color: white;
}
#elem2 {
padding: 20rem;
background: #fff;
}
#elem3 {
padding: 20rem;
background: #007;
}
#elem4 {
padding: 20rem;
background: #fff;
}
#flyingbox {
padding: 2rem;
width: 2rem;
left: 80%;
position: fixed;
top: 10px;
background: #fff;
}
.black {
background-color: black !important;
}
It doesn't look like you have an event listener to retrieve the current scroll position:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Get Bounding</title>
</head>
<body>
<div id="flyingbox">
</div>
<div class="elem oddElem" id="elem">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa blanditiis reprehenderit odio, eos
recusandae ipsam nulla quas sed voluptatum ex neque natus fuga illum dolores. Quis quibusdam odit, unde
minus?
</p>
</div>
<div class="elem evenElem" id="elem2">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa blanditiis reprehenderit odio, eos
recusandae ipsam nulla quas sed voluptatum ex neque natus fuga illum dolores. Quis quibusdam odit, unde
minus?
</p>
</div>
<div class="elem oddElem" id="elem3">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa blanditiis reprehenderit odio, eos
recusandae ipsam nulla quas sed voluptatum ex neque natus fuga illum dolores. Quis quibusdam odit, unde
minus?
</p>
</div>
<div class="elem evenElem" id="elem4">
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Culpa blanditiis reprehenderit odio, eos
recusandae ipsam nulla quas sed voluptatum ex neque natus fuga illum dolores. Quis quibusdam odit, unde
minus?
</p>
</div>
</body>
</html>
I have a side navigation menu on my site. When pressed, it calls a JavaScript function that changes the alpha channel of the body tag. For some reason only part of the screen's alpha channel is changing (section, img, bootstrap containers are not). The section tag has a class that gives it a background color, I'm thinking this might be the issue. Which would be the smart way to get this working?
This is the code I'm using for the alpha management:
/* Set the width of the side navigation to 250px */
function openNav() {
document.getElementById("mySidenav").style.width = "350px";
document.body.style.background = "rgba(0,0,0,0.4)";
}
/* Set the width of the side navigation to 0 */
function closeNav() {
document.getElementById("mySidenav").style.width = "0";
document.body.style.background = "rgba(0,0,0,0)";
}
The html goes like this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Cripto Frog</title>
<link rel="stylesheet" href="styles.css">
<link href="https://fonts.googleapis.com/css?family=Rammetto+One" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Lora" rel="stylesheet">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script defer src="https://use.fontawesome.com/releases/v5.0.8/js/all.js"></script>
<script src="sidebar.js"></script>
</head>
<main>
<header>
<span class="menu_burger" onclick="openNav()"><i class="fas fa-align-justify"></i></i></span>
<img src="img/frog.jpg" alt="">
</header>
<body>
<!-- Side Menu -->
<div id="mySidenav" class="sidenav">
×
TOP_TEN_COINS
ALT_COINS
WHITE_PAPERS
YOUTUBERS
EXCHANGES
NEWS_SITES
CONTACTO
<section class="nav_divididor"></section>
<section class="nav_footer">hlkjhlkjhlk</section>
</div>
<section class="primera_section"><p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam doloremque excepturi molestias aut fuga ullam aliquid minus dolores voluptatem non, beatae placeat soluta libero eos et delectus nemo minima iusto.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi error aspernatur officiis, sint fugiat unde quos labore laborum cupiditate voluptates, totam sunt ut quod praesentium omnis et consequuntur sapiente incidunt?Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit iure eveniet a voluptas cumque! Eos qui, iusto neque, fugit praesentium totam soluta eius laudantium cupiditate dolorem dignissimos ut minus veritatis.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla earum soluta nesciunt dicta officia reprehenderit autem, molestias explicabo et accusamus, officiis nostrum cumque perspiciatis suscipit veniam molestiae fuga tenetur modi!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate itaque atque molestiae, id fugit, quidem hic rem cum praesentium dolor perspiciatis nostrum sapiente enim corrupti doloremque aliquam voluptas cumque omnis.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam iusto dolor nostrum voluptate quos consectetur facere, quia, earum non, tenetur, officia laboriosam cumque suscipit itaque nobis obcaecati. Facilis veritatis, repudiandae.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Laboriosam doloremque excepturi molestias aut fuga ullam aliquid minus dolores voluptatem non, beatae placeat soluta libero eos et delectus nemo minima iusto.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Quasi error aspernatur officiis, sint fugiat unde quos labore laborum cupiditate voluptates, totam sunt ut quod praesentium omnis et consequuntur sapiente incidunt?Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugit iure eveniet a voluptas cumque! Eos qui, iusto neque, fugit praesentium totam soluta eius laudantium cupiditate dolorem dignissimos ut minus veritatis.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Nulla earum soluta nesciunt dicta officia reprehenderit autem, molestias explicabo et accusamus, officiis nostrum cumque perspiciatis suscipit veniam molestiae fuga tenetur modi!Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptate itaque atque molestiae, id fugit, quidem hic rem cum praesentium dolor perspiciatis nostrum sapiente enim corrupti doloremque aliquam voluptas cumque omnis.Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aperiam iusto dolor nostrum voluptate quos consectetur facere, quia, earum non, tenetur, officia laboriosam cumque suscipit itaque nobis obcaecati. Facilis veritatis, repudiandae.p</p>
</section>
<!-- Use any element to open the sidenav -->
</body>
<span onclick="openNav()">open</span>
</main>
<!-- Use any element to open the sidenav -->
<span onclick="openNav()">open</span>
</html>
css file
/* Secciones */
html{
margin-top: 0px;
/*overflow: hidden; */
}
body{
/* overflow-x: hidden;*/
}
p{
font-family: 'Lora';
font-style: normal;
font-weight: 700;
}
fieldset {
font-family: 'Lora';
font-style: normal;
font-weight: 100;
}
.nav_footer{
height: 90%;
background-color: black; /* Black*/
color: white;
display: flex;
align-items: flex-end;
/*overflow-x: hidden; */
}
.nav_divididor{
width: 100%;
background-color: #388E3C;
height: 12px;
}
.primera_section{
width: 100%;
height: 700px;
background-color: #FFFFFF; /* Black*/
}
.segunda_section{
width: 100%;
height: 700px;
background-color: #C8E6C9; /* Black*/
}
.tercera_section{
width: 100%;
height: 700px;
background-color: #BDBDBD; /* Black*/
}
.divisoria {
width: 100%;
background-color: black;
height: 2px;
}
.menu_burger{
position: absolute;
top:2;
}
/* The side navigation menu */
.sidenav {
height: 100%; /* 100% Full-height */
width: 0; /* 0 width - change this with JavaScript */
position: fixed; /* Stay in place */
z-index: 1; /* Stay on top */
top: 0; /* Stay at the top */
left: 0;
background-color: white; /* Dark Green*/
overflow-x: hidden; /* Disable horizontal scroll */
padding-top: 60px; /* Place content 60px from the top */
transition: 0.8s; /* 0.5 second transition effect to slide in the sidenav */
}
.sidenav::-webkit-scrollbar {
display: none;
}
/* The navigation menu links */
.sidenav a {
font-family: 'Lora';
font-style: normal;
font-weight: 700;
padding: 8px 8px 8px 32px;
text-decoration: none;
font-size: 25px;
color: black;
display: block;
transition: 0.3s;
}
/* When you mouse over the navigation links, change their color */
.sidenav a:hover {
color: grey;
}
/* Position and style the close button (top right corner) */
.sidenav .closebtn {
position: absolute;
top: 0;
right: 25px;
font-size: 36px;
margin-left: 50px;
}
/* Style page content - use this if you want to push the page content to the right when you open the side navigation */
#main {
transition: margin-left .5s;
padding: 20px;
}
/* On smaller screens, where height is less than 450px, change the style of the sidenav (less padding and a smaller font size) */
#media screen and (max-height: 450px) {
.sidenav {padding-top: 15px;}
.sidenav a {font-size: 18px;}
}