I wanted to know what I should add or change so that the w3schools tutorial is for multiple "modal boxes"
Link: https://www.w3schools.com/howto/howto_css_modals.asp
The idea is that the code is adapted and I can create as many "items" or "modal boxes" as I need, I try not to use jquery only javasript.
Note: the first "item" works correctly while the second "item" does not work.
Edit: I know that the same id can not be repeated in html, but in javascript when I change document.getElementById () by document.getElementsByClassName () the modal boxes does not work
CODE:
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
.item {
display: block;
overflow: hidden;
background-color: cyan;
margin: 10px 0;
}
.image {
width: 160px;
float: left;
}
.modal {
display: none;
position: fixed;
z-index 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.418);
}
.modal-content {
background-color: white;
margin: 15% auto;
padding: 20px;
width 80%;
}
.close {
float: right;
font-size: 20px;
font-weight: 700;
}
.close:hover, close:focus {
color: gold;
text-decoration: none;
cursor: pointer;
}
<div class="container">
<div class="item">
<img class="image" src="https://www.w3schools.com/w3css/img_avatar3.png" alt="">
<h2>Lorem, ipsum dolor.</h2>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eveniet, quos provident similique, itaque officiis eos dolorum fuga doloribus quo, aut saepe voluptatem pariatur deleniti. Laudantium fugit nesciunt voluptates magni consectetur!</p>
<button class="open-modal" id="myBtn">More Info</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">X</span>
<h2>Lorem, ipsum dolor.</h2>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum fugit minima ab, recusandae dolorum nam voluptatibus fuga possimus minus totam molestiae illum numquam autem? Placeat vero natus molestias soluta nemo.</p>
<button>Button</button>
<button>Button</button>
</div>
</div>
</div>
<div class="item">
<img class="image" src="https://www.w3schools.com/w3css/img_avatar3.png" alt="">
<h2>Lorem, ipsum dolor.</h2>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eveniet, quos provident similique, itaque officiis eos dolorum fuga doloribus quo, aut saepe voluptatem pariatur deleniti. Laudantium fugit nesciunt voluptates magni consectetur!</p>
<button class="open-modal" id="myBtn">More Info</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">X</span>
<h2>Lorem, ipsum dolor.</h2>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum fugit minima ab, recusandae dolorum nam voluptatibus fuga possimus minus totam molestiae illum numquam autem? Placeat vero natus molestias soluta nemo.</p>
<button>Button</button>
<button>Button</button>
</div>
</div>
</div>
</div>
ID's should be unique, you could add an onclick event on your buttons/span;
<button class="open-modal" id="myBtn" onclick="openModal('myModal');">More Info</button>
<span class="close" onclick="closeModal('myModal')">X</span>
Then openModal and closeModal functions should have the ID's of the target as parameter. See and run the code below.
var modal = "";
function openModal(target) {
modal = document.getElementById(target);
modal.style.display = "block";
}
function closeModal(target) {
modal = document.getElementById(target);
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
.item {
display: block;
overflow: hidden;
background-color: cyan;
margin: 10px 0;
}
.image {
width: 160px;
float: left;
}
.modal {
display: none;
position: fixed;
z-index 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0, 0, 0);
background-color: rgba(0, 0, 0, 0.418);
}
.modal-content {
background-color: white;
margin: 15% auto;
padding: 20px;
width 80%;
}
.close {
float: right;
font-size: 20px;
font-weight: 700;
}
.close:hover,
close:focus {
color: gold;
text-decoration: none;
cursor: pointer;
}
<div class="container">
<div class="item">
<img class="image" src="https://www.w3schools.com/w3css/img_avatar3.png" alt="">
<h2>Lorem, ipsum dolor.</h2>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eveniet, quos provident similique, itaque officiis eos dolorum fuga doloribus quo, aut saepe voluptatem pariatur deleniti. Laudantium fugit nesciunt voluptates magni consectetur!</p>
<button class="open-modal" id="myBtn" onclick="openModal('myModal');">More Info</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('myModal')">X</span>
<h2>Lorem, ipsum dolor.</h2>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum fugit minima ab, recusandae dolorum nam voluptatibus fuga possimus minus totam molestiae illum numquam autem? Placeat vero natus molestias soluta nemo.</p>
<button>Button</button>
<button>Button</button>
</div>
</div>
</div>
<div class="item">
<img class="image" src="https://www.w3schools.com/w3css/img_avatar3.png" alt="">
<h2>Lorem, ipsum dolor.</h2>
<p>Lorem ipsum, dolor sit amet consectetur adipisicing elit. Eveniet, quos provident similique, itaque officiis eos dolorum fuga doloribus quo, aut saepe voluptatem pariatur deleniti. Laudantium fugit nesciunt voluptates magni consectetur!</p>
<button class="open-modal" onclick="openModal('myModal2')">More Info</button>
<div id="myModal2" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal('myModal2')">X</span>
<h2>Lorem, ipsum dolor.</h2>
<p>Lorem ipsum dolor sit amet consectetur, adipisicing elit. Rerum fugit minima ab, recusandae dolorum nam voluptatibus fuga possimus minus totam molestiae illum numquam autem? Placeat vero natus molestias soluta nemo.</p>
<button>Button</button>
<button>Button</button>
</div>
</div>
</div>
</div>
Change the id of the modals. Id’s cannot repeat..
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 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 have a custom accordion, like jQuery UI accordion. I am also trying to make any expanded item collapsible (if it is clicked again). Something like this: https://jqueryui.com/accordion/#collapsible
But I am unable to figure out how to capture another click event on the currently expanded item. Can someone point me to the right direction?
<div class="dropdown">
<div class="style1 dropdown-link" style='background-color: rgb(75, 78, 80);'>Timecard Error Message</div>
<div class="style2 dropdown-container" style="display: none">
<div class="ExternalClassA37E015771DB4A43AFAA85E21F07E758">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque sapiente beatae eum repudiandae aliquam possimus delectus veritatis numquam sit eaque esse quos ipsa, pariatur omnis obcaecati quibusdam dolore magnam!
</p>
</div>
</div>
</div>
<div class="dropdown">
<div class="style1 dropdown-link" style="background-color: rgb(84, 88, 90);">Worklist Emails</div>
<div class="style2 dropdown-container" style="display: none;">
<div class="ExternalClassA7D39E7BCBCE48A791E0F84E3631CC00">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque sapiente beatae eum repudiandae aliquam possimus delectus veritatis numquam sit eaque esse quos ipsa, pariatur omnis obcaecati quibusdam dolore magnam!
</div>
</div>
</div>
and my jQuery is sth like below:
$(document).ready(function(){
$('div.dropdown').each(function() {
var $dropdown = $(this);
$(".dropdown-link", $dropdown).click(function(e) {
e.preventDefault();
$("div.dropdown-link").css('background-image',''); //reset the background so CSS Background takes over
$("div.dropdown-container").css('display','none');
$("div.dropdown-link").css('background-color','#54585a');
$("div.dropdown-link").css('border','none');
if($("div.dropdown-container", $dropdown).css('display','none')){
$("div.dropdown-link", $dropdown).css('background-color','#4b4e50');
$("div.dropdown-link", $dropdown).css({'border-bottom':'1px dotted white', 'border-top':'1px dotted white'});
$("div.dropdown-container", $dropdown).css('display','inline-block');
$("div.dropdown-link", $dropdown).css('background-image','url("/SiteAssets/arrowdown.png")');
}else{
$("div.dropdown-link", $dropdown).css('background-image','url("/SiteAssets/img/arrow.png")');
$("div.dropdown-container", $dropdown).css('display','none');
$("div.dropdown-link", $dropdown).css('background-color','#54585a');
$("div.dropdown-link", $dropdown).css('border', 'none');
}
return false;
});
});
});
Here is the jsbin: http://jsbin.com/hazaxunuwa/edit?html,css,js,output
Its not a good idea to use JavaScript for changing a lot of styles while you can do it with just css. You should only include one class on your .dropdown when it is active. Below is the sample code where I've moved all your styles to css:
$(document).ready(function(){
$('div.dropdown').each(function() {
var $dropdown = $(this);
var $dropdownLink = $dropdown.find('.dropdown-link');
$dropdownLink.click(function(e) {
e.preventDefault();
var currentBlock = $(this).closest('.dropdown');
if(currentBlock.hasClass('slide-active')) {
currentBlock.removeClass('slide-active');
} else {
$('div.dropdown').removeClass('slide-active');
currentBlock.addClass('slide-active');
}
});
});
});
.dropdown-link {
background: #54585a;
}
.dropdown-container {
display: none;
}
.slide-active .dropdown-container {
display: block;
}
.slide-active .dropdown-link {
border-bottom: 1px dotted white;
background: #4b4e50;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="dropdown">
<div class="style1 dropdown-link">Timecard Error Message</div>
<div class="style2 dropdown-container">
<div class="ExternalClassA37E015771DB4A43AFAA85E21F07E758">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque sapiente beatae eum repudiandae aliquam possimus delectus veritatis numquam sit eaque esse quos ipsa, pariatur omnis obcaecati quibusdam dolore magnam!
</p>
</div>
</div>
</div>
<div class="dropdown">
<div class="style1 dropdown-link">Worklist Emails</div>
<div class="style2 dropdown-container">
<div class="ExternalClassA7D39E7BCBCE48A791E0F84E3631CC00">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque sapiente beatae eum repudiandae aliquam possimus delectus veritatis numquam sit eaque esse quos ipsa, pariatur omnis obcaecati quibusdam dolore magnam!
</div>
</div>
</div>
<div class="dropdown">
<div class="style1 dropdown-link">Unable to Enter a Future Timecard</div>
<div class="style2 dropdown-container">
<div class="ExternalClassD8605E4C12364C5685331D8368E84E8A">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque sapiente beatae eum repudiandae aliquam possimus delectus veritatis numquam sit eaque esse quos ipsa, pariatur omnis obcaecati quibusdam dolore magnam!
</div>
</div>
</div>
Alternatively, by making use of the index value of the .each() function, when the user clicks on a title, we loop through the content array and for the matching item we use toggleClass() to toggle the class .expand which is responsible for expanding the content section, and for each not matching item we remove this class.
jsFiddle
var titles = $('.title'),
content = $('.content');
titles.each(function(index) {
$(this).on('click', function() {
for (var i = 0; i < content.length; ++i) {
if (i == index) {
$(content[i]).toggleClass('expand');
} else {
$(content[i]).removeClass('expand');
}
}
});
});
.accord { width: 500px; outline: 1px solid #aaa; }
.title { color: white; background-color: #555; padding: 10px 5px; cursor: pointer; }
.content { max-height: 1px; overflow: hidden; }
.expand { max-height: 1000px; padding: 5px 5px 20px 5px; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="accord">
<div class="title">This is title ONE</div>
<div class="content">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Temporibus debitis, ipsum at asperiores dignissimos aperiam qui. Dignissimos mollitia incidunt commodi, necessitatibus numquam corporis, ex expedita ut consequatur maiores doloremque eius.
</div>
<div class="title">This is title TWO</div>
<div class="content">Cake gummies candy canes topping donut caramels candy bear claw. Powder brownie chupa chups macaroon jelly beans chocolate chocolate jelly. Chupa chups apple pie marshmallow dessert tart apple pie cotton candy tiramisu. Fruitcake cupcake pie. Cheesecake
bear claw croissant candy tart. Liquorice cookie candy topping macaroon.
</div>
<div class="title">And here's title THREE</div>
<div class="content">Percolator, spoon half and half variety saucer caramelization qui milk. Sugar aromatic white at skinny roast redeye decaffeinated shop. Siphon spoon id, robust froth doppio redeye café au lait. So aroma, a grinder crema froth acerbic. Cultivar ristretto
carajillo turkish galão cappuccino, roast to go black body milk. Est decaffeinated seasonal coffee robust, qui sit french press single shot single origin.
</div>
</div>
Avoid styling in javascript, it would be a bad practice.
Here is the snippet of what you want.
$(document).ready(function(){
$('div.dropdown').each(function() {
var $dropdown = $(this);
$(".dropdown-link", $dropdown).click(function(e) {
e.preventDefault();
var parent_drop = $(this).closest(".dropdown");
if($(parent_drop).is(".open")){
$(parent_drop).removeClass("open");
$("div.dropdown-container").css('display','none');
} else {
$(parent_drop).addClass("open");
$("div.dropdown-link").css('background-image',''); //reset the background so CSS Background takes over
$("div.dropdown-container").css('display','none');
$("div.dropdown-link").css('background-color','#54585a');
$("div.dropdown-link").css('border','none');
if($("div.dropdown-container", $dropdown).css('display','none')){
$("div.dropdown-link", $dropdown).css('background-color','#4b4e50');
$("div.dropdown-link", $dropdown).css({'border-bottom':'1px dotted white', 'border-top':'1px dotted white'});
$("div.dropdown-container", $dropdown).css('display','inline-block');
$("div.dropdown-link", $dropdown).css('background-image','url("/SiteAssets/arrowdown.png")');
}else{
$("div.dropdown-link", $dropdown).css('background-image','url("/SiteAssets/img/arrow.png")');
$("div.dropdown-container", $dropdown).css('display','none');
$("div.dropdown-link", $dropdown).css('background-color','#54585a');
$("div.dropdown-link", $dropdown).css('border', 'none');
}
}
return false;
});
});
});
.style1 {
font-family: "Segoe UI","Segoe",Tahoma,Helvetica,Arial,sans-serif;
font-size: 13px;
color: #fff; line-height:22px; cursor: pointer; background-color:#5d6264; padding-left:3px; margin-left:5px;
background: url('/SiteAssets/img/gt2.png') no-repeat center left;
background-size:12px 12px;
padding-left: 15px;
}
.style2 {
font-family: "Segoe UI","Segoe",Tahoma,Helvetica,Arial,sans-serif;
font-size: 13px;
border-bottom:1px dotted silver;
padding:0px 5px 5px 15px; margin-left:5px; background-color:#606567; color:#fff; display:none;
}
.style2 a{color: white !important; text-decoration:underline !important;}
.style3{
font-family: "Segoe UI","Segoe",Tahoma,Helvetica,Arial,sans-serif;
font-size: 13px; font-weight:bold; color:#fff;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="dropdown">
<div class="style1 dropdown-link" style='background-color: rgb(75, 78, 80);'>Timecard Error Message</div>
<div class="style2 dropdown-container" style="display: none">
<div class="ExternalClassA37E015771DB4A43AFAA85E21F07E758">
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque sapiente beatae eum repudiandae aliquam possimus delectus veritatis numquam sit eaque esse quos ipsa, pariatur omnis obcaecati quibusdam dolore magnam!
</p>
</div>
</div>
</div>
<div class="dropdown">
<div class="style1 dropdown-link" style="background-color: rgb(84, 88, 90);">Worklist Emails</div>
<div class="style2 dropdown-container" style="display: none;">
<div class="ExternalClassA7D39E7BCBCE48A791E0F84E3631CC00">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur atque sapiente beatae eum repudiandae aliquam possimus delectus veritatis numquam sit eaque esse quos ipsa, pariatur omnis obcaecati quibusdam dolore magnam!
</div>
</div>
</div>
I am trying to use jQuery to set a set of div to the heigh of the tallest div. I have got the initial function working, where it gets the site and applies it to the rest of the divs on the page.
I also am trying to recalculate the heigh of the div in resize. In the JSfiddle, you can see that when you shrink the text expands out of the card/div.
I have tried to put the function into the resize function however in doesn't re-fire. I'm not sure what i am doing wrong.
I'm a JS beginner, apologies.
HTML
<div class="fluid-container grey-bg">
<div class="container">
<div class="card-default width-25 items">
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloremque hic aliquid ea id, perferendis mollitia nam consequatur, ut rerum animi nisi iste, quae provident atque placeat repudiandae impedit delectus sequi.
</div>
</div>
<div class="card-default width-25 spacer items">
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Doloremque ex sed voluptatum rem iste
</div>
</div>
<div class="card-default width-25 spacer items">
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Corporis omnis, quos id quaerat magni nobis blanditiis, esse magnam provident cupiditate harum non! Modi cupiditate earum eos repudiandae impedit nemo repellendus!
</div>
</div>
<div class="card-default width-25 items">
<div class="content">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aliquid laboriosam magni placeat numquam
</div>
</div>
</div>
</div>
CSS
.card-default {
background-color: #fff;
border-radius: 10px;
color: #333333;
min-height: 100px;
box-shadow: 0px 6px 7px 0px rgba(0, 0, 0, 0.25);
box-sizing: border-box;
padding: 20px 0px;
text-align: center;
margin-bottom: 20px;
display: block;
float: left;
position: relative;
width: 100%;
}
.card-default.width-25 {
width: 23%;
margin-left: 0px;
margin-right: 0px;
padding: 20px 20px;
}
JS
function cardEqualHeight() {
var maxHeight = -1;
$('.items').each(function() {
maxHeight = maxHeight >= $(this).height() ? maxHeight : $(this).height();
});
$('.items .content').each(function() {
$(this).height(maxHeight);
});
}
cardEqualHeight();
https://jsfiddle.net/k3lh4m/7wmfox9m/
Add this to the containter class and don't use your JS function and there you go!
.container {
display: flex;
flex-wrap: wrap;
}
jsfiddle