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>
Related
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 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>
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>
Is it possible to apply scroll-snap to grand-children nested in children with overflow applied ? I can't seem to make it work.
What I aim to do is have a list of div with each a fixed height on which the viewport should snap vertically
html {
margin: 0;
scroll-snap-type: y mandatory;
overflow-x: hidden;
}
.horizontal-scroll {
max-width: 100vw;
}
.child {
width: 150vw;
scroll-snap-align: center;
height: 80vh;
background-color: rgb(143, 204, 241);
padding: 20px 15px;
}
.child:nth-child(even) {
background-color: rgb(133, 243, 155);
}
<!DOCTYPE html>
<html>
<head
</head>
<body>
<div class="horizontal-scroll">
<div class="child">
<h2>Section</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel laboriosam cupiditate vero, harum, ab facere ipsa mollitia exercitationem impedit alias nulla magnam aut tempore repudiandae
dolores. Sit maiores nemo ea.
</p>
</div> <div class="child">
<h2>Section</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel laboriosam cupiditate vero, harum, ab facere ipsa mollitia exercitationem impedit alias nulla magnam aut tempore repudiandae
dolores. Sit maiores nemo ea.
</p>
</div>
<div class="child">
<h2>Section</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel laboriosam cupiditate vero, harum, ab facere ipsa mollitia exercitationem impedit alias nulla magnam aut tempore repudiandae
dolores. Sit maiores nemo ea.
</p>
</div>
</div>
</body>
</html>
Homewer, I would also like the content to be horizontally-scrollable - as their content stretch beyond the viewport width.
They must also scroll together, so using overflow-x on each of them is not possible here.
To do so, I've wrapped the child in a scrollable-wrapper that is horizontally scrollable ( overflow-x : scroll ) and have a fixed width.
And this breaks the vertical scroll snap.
Could someone tell me if there's something I missed or if there's an alternative ?
Note : since each child have a fixed height, I would not mind using scroll-snap-points-y but it has been totally dropped on almost every browser. Is there a way to reproduce this behaviour ?
Edit : I might try this for the snap-point. It's jQuery based.
Vertical scrolling snap jQuery
Snippet
html {
margin: 0;
scroll-snap-type: y mandatory;
overflow-x: hidden;
}
.horizontal-scroll {
max-width: 100vw;
overflow-x: scroll;
}
.child {
width: 150vw;
scroll-snap-align: center;
height: 80vh;
background-color: rgb(143, 204, 241);
padding: 20px 15px;
}
.child:nth-child(even) {
background-color: rgb(133, 243, 155);
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div class="horizontal-scroll">
<div class="child">
<h2>Section</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel laboriosam cupiditate vero, harum, ab facere ipsa mollitia exercitationem impedit alias nulla magnam aut tempore repudiandae
dolores. Sit maiores nemo ea.
</p>
</div> <div class="child">
<h2>Section</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel laboriosam cupiditate vero, harum, ab facere ipsa mollitia exercitationem impedit alias nulla magnam aut tempore repudiandae
dolores. Sit maiores nemo ea.
</p>
</div>
<div class="child">
<h2>Section</h2>
<p>
Lorem ipsum dolor sit amet consectetur adipisicing elit. Vel laboriosam cupiditate vero, harum, ab facere ipsa mollitia exercitationem impedit alias nulla magnam aut tempore repudiandae
dolores. Sit maiores nemo ea.
</p>
</div>
</div>
</body>
</html>
I want to set display property none with on click event. If I am using querySelectorAll then it's applyng on all if I click on first button and other buttons are not working. I am New to JavaScript Here is my code.
let div = document.querySelector('.cross')
div.addEventListener('click',closeDiv);
function closeDiv() {
let closeBy = document.querySelectorAll('div');
closeBy.forEach(element => {
element.classList.add('display')
});
}
div{
border: 1px solid green;
margin: 5px;
text-align: center;
padding: 10px
}
.cross {
border: 1px solid red;
border-radius: 5px;
position: absolute;
right: 27px;
background-color: red;
color: white;
cursor: pointer;
}
.cross:hover {
background-color: greenyellow;
border: 1px solid greenyellow;
color: red;
}
.display{
display: none;
}
<div>
<button class="cross">X</button>
<h3>First</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam atque dignissimos, delectus facere vero quia, similique voluptatem adipisci nobis iusto suscipit. Consequuntur officia earum iure! Consequatur iusto soluta ut alias atque blanditiis, optio maiores ullam, cum quibusdam, adipisci hic ducimus sed nam quas. </p>
</div>
<div>
<button class="cross">X</button>
<h3>Second</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam atque dignissimos, delectus facere vero quia, similique voluptatem adipisci nobis iusto suscipit. Consequuntur officia earum iure! Consequatur iusto soluta ut alias atque blanditiis, optio maiores ullam, cum quibusdam, adipisci hic ducimus sed nam quas. </p></div>
<div>
solution for clicking a div and its parent div will hide
Step 1: add function closeDiv() to every div which are responsible to closing div
<div>
<button class="cross" onClick="closeDiv(event)">X</button>
<h3>First</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam atque dignissimos, delectus facere vero quia, similique voluptatem adipisci nobis iusto suscipit. Consequuntur officia earum iure! Consequatur iusto soluta ut alias atque blanditiis, optio maiores ullam, cum quibusdam, adipisci hic ducimus sed nam quas. </p>
</div>
<div>
<button class="cross" onClick="closeDiv(event)">X</button>
<h3>Second</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam atque dignissimos, delectus facere vero quia, similique voluptatem adipisci nobis iusto suscipit. Consequuntur officia earum iure! Consequatur iusto soluta ut alias atque blanditiis, optio maiores ullam, cum quibusdam, adipisci hic ducimus sed nam quas. </p>
</div>
<div> // This line is incorrect in your code
Step 2: add functional things in side closeDiv function
function closeDiv(event) {
let wrapperDiv = event.target.parentNode
wrapperDiv.style.display = "none"
}
Check the full code here
Hope this helps and feel free to comment below if this answer is not enough to you.
I just changed the javascript code
let cross = document.querySelectorAll('.cross')
cross.forEach(function(element) {
element.addEventListener('click', function(event) {
this.parentElement.style.display = 'none' // get parent
})
})
Eu quero definir nenhuma propriedade de exibição no evento click. Se eu estiver usando o querySelectorAll, será aplicado a todos se clicar no primeiro botão e outros botões não estiverem funcionando. Eu sou novo no JavaScript Aqui está o meu código.
let div = document.querySelector('.cross')
div.addEventListener('click',closeDiv);
function closeDiv() {
let closeBy = document.querySelectorAll('div');
closeBy.forEach(element => {
element.classList.add('display')
});
}
div{
border: 1px solid green;
margin: 5px;
text-align: center;
padding: 10px
}
.cross {
border: 1px solid red;
border-radius: 5px;
position: absolute;
right: 27px;
background-color: red;
color: white;
cursor: pointer;
}
.cross:hover {
background-color: greenyellow;
border: 1px solid greenyellow;
color: red;
}
.display{
display: none;
}
<div>
<button class="cross">X</button>
<h3>First</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam atque dignissimos, delectus facere vero quia, similique voluptatem adipisci nobis iusto suscipit. Consequuntur officia earum iure! Consequatur iusto soluta ut alias atque blanditiis, optio maiores ullam, cum quibusdam, adipisci hic ducimus sed nam quas. </p>
</div>
<div>
<button class="cross">X</button>
<h3>Second</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam atque dignissimos, delectus facere vero quia, similique voluptatem adipisci nobis iusto suscipit. Consequuntur officia earum iure! Consequatur iusto soluta ut alias atque blanditiis, optio maiores ullam, cum quibusdam, adipisci hic ducimus sed nam quas. </p></div>
<div>
Use parentElement to get the parent element
I'd use dataset attributes so each button knows what it closes.
In current example you could target parent object, but I prefer using dataset attributes because this can be applied even if close button gets nested deeper and div isn't direct parent anymore
let div = document.querySelectorAll('.cross')
div.forEach(element => {
element.addEventListener('click',closeDiv);
});
function closeDiv() {
let parentMessageId = this.dataset.parentmessage;
let closeBy = document.querySelectorAll('[data-message="'+parentMessageId+'"]');
closeBy.forEach(element => {
element.classList.add('display-hidden')
});
}
div{
border: 1px solid green;
margin: 5px;
text-align: center;
padding: 10px
}
.cross {
border: 1px solid red;
border-radius: 5px;
position: absolute;
right: 27px;
background-color: red;
color: white;
cursor: pointer;
}
.cross:hover {
background-color: greenyellow;
border: 1px solid greenyellow;
color: red;
}
.display-hidden{
display: none;
}
<div data-message="1">
<button data-parentmessage="1" class="cross">X</button>
<h3>First</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam atque dignissimos, delectus facere vero quia, similique voluptatem adipisci nobis iusto suscipit. Consequuntur officia earum iure! Consequatur iusto soluta ut alias atque blanditiis, optio maiores ullam, cum quibusdam, adipisci hic ducimus sed nam quas. </p>
</div>
<div data-message="2">
<button data-parentmessage="2" class="cross">X</button>
<h3>Second</h3>
<p>Lorem ipsum dolor sit amet consectetur adipisicing elit. Ipsam atque dignissimos, delectus facere vero quia, similique voluptatem adipisci nobis iusto suscipit. Consequuntur officia earum iure! Consequatur iusto soluta ut alias atque blanditiis, optio maiores ullam, cum quibusdam, adipisci hic ducimus sed nam quas. </p>
</div>