How can I get this flexbox to expand with it's flex items? [duplicate] - javascript

This question already has answers here:
Flex elements ignore percent padding in Firefox
(4 answers)
Closed 4 years ago.
In my example code, please click on the Generate Content button in order to understand the issue.
Once you click on the button, you can see all of the flex items(.each-result) generate. They are almost completely wrapped by the div/flexbox (.result-container), indicated by the blue dotted border. If I remove the margins from flex-items, it fits perfectly into the div. However, when I add the margins, the parent div (ie. the flexbox) doesn't expand to it's full width; it remains the same width as when there was no margin.
Is there anyway to change this so that the div expands when adding margin?
const leftArrow = document.querySelector('#left-arrow');
const rightArrow = document.querySelector('#right-arrow');
const rootDiv = document.querySelector('#root');
const generateButton = document.querySelector("#button-generate");
var navMargin = '';
let rootContainerWidth = window.getComputedStyle(rootDiv, null).getPropertyValue("width");
console.log(`Window size onload: ${rootContainerWidth}`);
window.addEventListener('resize', () => {
rootContainerWidth = window.getComputedStyle(rootDiv, null).getPropertyValue("width");
console.log(`The new window size is ${rootContainerWidth}`);
})
//This code basically generates the content within the div
generateButton.addEventListener("click", () => {
for (let i = 0; i < 10; i++) {
const newDiv = document.createElement("div");
newDiv.classList.add("each-result");
newDiv.appendChild(addImg("https://uk.usembassy.gov/wp-content/uploads/sites/16/please_read_icon_150x150.jpg"));
rootDiv.appendChild(newDiv);
}
rootDiv.firstElementChild.classList.add('nav-margin');
navMargin = document.querySelector('.nav-margin');
});
//These enable the arrow to scroll through the dynamically generated content
// function navArrow () {
// leftArrow.addEventListener('click', () => {
// });
// rightArrow.addEventListener('click', () => {
// if ()
// });
// }
//Simple function to create and image element with the src attribute set in one line
function addImg(url) {
const newImg = document.createElement("img");
newImg.setAttribute("src", url);
return newImg;
}
html, body {
height: 100%;
}
button {
position: relative;
z-index: 1
width: auto;
height: 50px;
}
.container {
display: flex;
justify-content: center;
position: relative;
top: 15%;
z-index: 0
}
.each-result {
height: 150px;
width: 150px;
border: 3px dotted red;
margin: 0 1%;
}
img {
height: 100%;
width: auto;
}
.nav-arrows {
display: flex;
justify-content: space-between;
width: 100%;
height: auto;
position: absolute;
background: clear;
pointer-events: none;
}
#left-arrow, #right-arrow {
pointer-events: auto;
}
#root-container {
display: flex;
align-items: center;
border: 1px solid black;
height: 200px;
position: relative;
flex-flow: row no-wrap;
/* overflow: hidden; */
width: 100%;
}
.result-container {
display: flex;
border: 2px blue dotted;
}
<script src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<div class="container">
<div class="nav-arrows">
<button id="left-arrow"><i class="fas fa-arrow-alt-circle-left"></i>
</button>
<button id="right-arrow"> <i class="fas fa-arrow-alt-circle-right"></i>
</button>
</div>
<div id="root-container">
<div id="root" class="result-container">
</div>
</div>
</div>
<button id="button-generate">Generate Content</button>

If the margin can be a fixed value (instead of a percent), we can calc() the width of the element to account for the margin. For example, if we wanted a margin of 20px we'd do the following on the .each-result elements:
.each-result {
width: calc(10% + 20px);
margin: 0 20px;
}
Here's the working demo:
const leftArrow = document.querySelector('#left-arrow');
const rightArrow = document.querySelector('#right-arrow');
const rootDiv = document.querySelector('#root');
const generateButton = document.querySelector("#button-generate");
var navMargin = '';
let rootContainerWidth = window.getComputedStyle(rootDiv, null).getPropertyValue("width");
console.log(`Window size onload: ${rootContainerWidth}`);
window.addEventListener('resize', () => {
rootContainerWidth = window.getComputedStyle(rootDiv, null).getPropertyValue("width");
console.log(`The new window size is ${rootContainerWidth}`);
})
//This code basically generates the content within the div
generateButton.addEventListener("click", () => {
for (let i = 0; i < 10; i++) {
const newDiv = document.createElement("div");
newDiv.classList.add("each-result");
newDiv.appendChild(addImg("https://uk.usembassy.gov/wp-content/uploads/sites/16/please_read_icon_150x150.jpg"));
rootDiv.appendChild(newDiv);
}
rootDiv.firstElementChild.classList.add('nav-margin');
navMargin = document.querySelector('.nav-margin');
});
//These enable the arrow to scroll through the dynamically generated content
// function navArrow () {
// leftArrow.addEventListener('click', () => {
// });
// rightArrow.addEventListener('click', () => {
// if ()
// });
// }
//Simple function to create and image element with the src attribute set in one line
function addImg(url) {
const newImg = document.createElement("img");
newImg.setAttribute("src", url);
return newImg;
}
html, body {
height: 100%;
}
button {
position: relative;
z-index: 1
width: auto;
height: 50px;
}
.container {
display: flex;
justify-content: center;
position: relative;
top: 15%;
z-index: 0
}
.each-result {
height: 150px;
width: calc(10% + 20px);
margin: 0 20px;
border: 3px dotted red;
}
img {
height: 100%;
width: auto;
}
.nav-arrows {
display: flex;
justify-content: space-between;
width: 100%;
height: auto;
position: absolute;
background: clear;
pointer-events: none;
}
#left-arrow, #right-arrow {
pointer-events: auto;
}
#root-container {
display: flex;
align-items: center;
border: 1px solid black;
height: 200px;
position: relative;
flex-flow: row no-wrap;
/* overflow: hidden; */
width: 100%;
}
.result-container {
display: flex;
border: 2px blue dotted;
}
<script src="https://use.fontawesome.com/releases/v5.0.6/js/all.js"></script>
<div class="container">
<div class="nav-arrows">
<button id="left-arrow"><i class="fas fa-arrow-alt-circle-left"></i>
</button>
<button id="right-arrow"> <i class="fas fa-arrow-alt-circle-right"></i>
</button>
</div>
<div id="root-container">
<div id="root" class="result-container">
</div>
</div>
</div>
<button id="button-generate">Generate Content</button>

Related

Creating a Simple image carousel using JS Array

I created a simple carousel using HTML, CSS, and Javascript.
Clicking the left button shows the previous slide and the right one shows the next slide.
But my concern is that slide change is not working correctly
when clicking the next button: After the final slide, it won't go to the first slide again.
when clicking the previous button: After the first slide, it won't go again to last the slide again.
So please review my code and let me know my error.
let right = document.querySelector('.nxt');
let left = document.querySelector('.pre');
let slids = document.querySelector('.slids');
let first = document.querySelector('.first');
let scond = document.querySelector('.scond');
let third = document.querySelector('.third');
let fouth = document.querySelector('.fouth');
let slidesArray=[first,scond,third,fouth];
let index= 0;
let activeSlide= slidesArray[index].classList.add('active');
left.addEventListener('click',()=>{
if (++index > 0) {
slidesArray[index].classList.add('active');
}
});
right.addEventListener('click',()=>{
if (index > 0) {
slidesArray[index].classList.add('deactive');
slidesArray[--index].classList.add('active');
}
});
body{
display: flex;
justify-content: center;
align-items: center;
}
.slids>*{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% ,-50%);
width: 400px;
height: 350px;
font-size: 50px;
font-weight: 600;
display: grid;
place-items: center;
border-radius: 20px;
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
visibility: hidden;
}
.active{
visibility: visible;
}
.first{
background-color: #F7EC09;
}
.scond{
background-color: #3EC70B;
}
.third{
background-color: #3B44F6;
}
.fouth{
background-color: #A149FA;
}
.btn{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% ,-50%);
display: flex;
gap: 450px;
}
.nxt, .pre{
font-size: 100px;
font-weight: 700;
background: none;
border: none;
cursor: pointer;
}
<body>
<div class="slids">
<div class="first">1</div>
<div class="scond">2</div>
<div class="third">3</div>
<div class="fouth">4</div>
</div>
<div class="btn">
<button class="nxt"><</button>
<button class="pre">></button>
</div>
A chained ternary expression can be used to determine the new index number in a single line:
to = to >= size ? 0 : to < 0 ? size - 1 : to;
Details are commented in example
// Reference the buttons
let next = document.querySelector('.next');
let prev = document.querySelector('.prev');
/*
Collect all div.slide into an array
Define the array's size
Define a number value outside of the function
*/
let slides = [...document.querySelectorAll('.slide')];
let size = slides.length;
let index = 0;
// Bind click event to button.prev
prev.onclick = event => move(index - 1);
// Bind click event to button.next
next.onclick = event => move(index + 1);
/*
Pass newest index number
Ternary expression:
If the given number is greater than or equal to size of the array...
...return 0...
...If the given number is less than 0...
...return last index of array...
...otherwise return the given number
Toggle the current .slide.active and new .slide
Assign index as the given number
*/
function move(to) {
to = to >= size ? 0 : to < 0 ? size - 1 : to;
slides[index].classList.toggle("active");
slides[to].classList.toggle("active");
index = to;
}
html {
font: 300 3vmin/1 Consolas;
}
body {
display: flex;
justify-content: center;
align-items: center;
}
main {
display: flex;
justify-content: center;
align-items: center;
position: relative;
max-width: max-content;
min-height: 100vh;
}
.slides {
display: flex;
justify-content: center;
align-items: center;
position: relative;
width: 420px;
height: 400px;
overflow: hidden;
}
.slide {
display: grid;
place-items: center;
position: absolute;
top: 50%;
left: 50%;
width: 400px;
height: 350px;
border-radius: 20px;
font-size: 50px;
font-weight: 600;
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
visibility: hidden;
transform: translate(-50%, -50%);
}
.active {
visibility: visible;
}
.slide:first-of-type {
background-color: #F7EC09;
}
.slide:nth-of-type(2) {
background-color: #3EC70B;
}
.slide:nth-of-type(3) {
background-color: #3B44F6;
}
.slide:nth-of-type(4) {
background-color: #A149FA;
}
.ctrl {
display: flex;
justify-content: space-between;
position: absolute;
top: 45%;
left: 45%;
width: 150%;
transform: translate(-50%, -50%);
}
.next,
.prev {
border: none;
font-size: 100px;
font-weight: 700;
background: none;
cursor: pointer;
}
<main>
<section class="slides">
<div class="slide active">1</div>
<div class="slide">2</div>
<div class="slide">3</div>
<div class="slide">4</div>
</section>
<menu class="ctrl">
<button class="prev"><</button>
<button class="next">></button>
</menu>
</main>
You need to reset the index of the slide when you click next and reach to maximum slide you need to reset index to 0 to return to first slide, also when you click prev and you in the first slide, you need to reset index to 3 to return the last slide.
let right = document.querySelector(".nxt");
let left = document.querySelector(".pre");
let slids = document.querySelector(".slids");
let first = document.querySelector(".first");
let scond = document.querySelector(".scond");
let third = document.querySelector(".third");
let fouth = document.querySelector(".fouth");
const elementsArr = [first, scond, third, fouth];
let slidesArray = [first, scond, third, fouth];
let index = 0;
let activeSlide = slidesArray[index].classList.add("active");
left.addEventListener("click", () => {
if (index === 3) {
index = -1;
}
index++;
resetActiveElements()
});
right.addEventListener("click", () => {
if (index === 0) index = 4;
index--;
resetActiveElements()
});
const resetActiveElements = () => {
elementsArr.forEach((element, i) => {
if (index === i) {
element.classList.add("active");
} else {
element.classList.remove("active");
}
});
}
body{
display: flex;
justify-content: center;
align-items: center;
}
.slids>*{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% ,-50%);
width: 400px;
height: 350px;
font-size: 50px;
font-weight: 600;
display: grid;
place-items: center;
border-radius: 20px;
box-shadow: rgba(0, 0, 0, 0.24) 0px 3px 8px;
visibility: hidden;
}
.active{
visibility: visible;
}
.first{
background-color: #F7EC09;
}
.scond{
background-color: #3EC70B;
}
.third{
background-color: #3B44F6;
}
.fouth{
background-color: #A149FA;
}
.btn{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50% ,-50%);
display: flex;
gap: 450px;
}
.nxt, .pre{
font-size: 100px;
font-weight: 700;
background: none;
border: none;
cursor: pointer;
}
<body>
<div class="slids">
<div class="first">1</div>
<div class="scond">2</div>
<div class="third">3</div>
<div class="fouth">4</div>
</div>
<div class="btn">
<button class="nxt"><</button>
<button class="pre">></button>
</div>
/* <div class="btn">
<button class="pre"><</button>
<button class="nxt">></button>
</div> */
let right = document.querySelector('.nxt');
let left = document.querySelector('.pre');
let slids = document.querySelector('.slids');
let first = document.querySelector('.first');
let scond = document.querySelector('.scond');
let third = document.querySelector('.third');
let fouth = document.querySelector('.fouth');
let slidesArray = [first, scond, third, fouth];
let index = 0;
let activeSlide = slidesArray[index].classList.add('active');
left.addEventListener('click', () => {
slidesArray[index].classList.remove('active');
if (index == 0) {
index = 3;
slidesArray[index].classList.add('active');
} else {
index--;
slidesArray[index].classList.add('active');
}
});
right.addEventListener('click', () => {
slidesArray[index].classList.remove('active');
if (index == 3) {
index = 0;
slidesArray[index].classList.add('active');
} else {
index++;
slidesArray[index].classList.add('active');
}
});

API images not displayed within modal

I am a beginner and I am using several tutorials to learn and create a project. I am using the NASA APOD API to display images. However, I want to display the image when clicked within a modal. For some reason the image when clicked is displaying the modal, but without the image. How do I click on the image and display it within the modal.
const resultsNav = document.getElementById("resultsNav");
const favoritesNav = document.getElementById("favoritesNav");
const imagesContainer = document.querySelector(".images-container");
const saveConfirmed = document.querySelector(".save-confirmed");
const loader = document.querySelector(".loader");
// NASA API
const count = 3;
const apiKey = 'DEMO_KEY';
const apiUrl = `https://api.nasa.gov/planetary/apod?api_key=${apiKey}&count=${count}`;
let resultsArray = [];
let favorites = {};
// Show Content
function showContent(page) {
window.scrollTo({ top: 0, behavior: "instant" });
if (page === "results") {
resultsNav.classList.remove("hidden");
favoritesNav.classList.add("hidden");
} else {
resultsNav.classList.add("hidden");
favoritesNav.classList.remove("hidden");
}
loader.classList.add("hidden");
}
// Create DOM Nodes
function createDOMNodes(page) {
const currentArray =
page === "results" ? resultsArray : Object.values(favorites);
currentArray.forEach((result) => {
// Card Container
const card = document.createElement("div");
card.classList.add("card");
// Link that wraps the image
const link = document.createElement("a");
// link.href = result.hdurl; -- full size image display when clicked
// Get the modal
var modal = document.getElementById("myModal");
// Get the image and insert it inside the modal - use its "alt" text as a caption
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// Image
const image = document.createElement("img");
image.src = result.url;
image.alt = "NASA Picture of the Day";
image.loading = "lazy";
image.classList.add("card-img-top");
// Card Body
const cardBody = document.createElement("div");
cardBody.classList.add("card-body");
// Card Title
const cardTitle = document.createElement("h5");
cardTitle.classList.add("card-title");
cardTitle.textContent = result.title;
// Save Text
const saveText = document.createElement("p");
saveText.classList.add("clickable");
if (page === "results") {
saveText.textContent = "Add To Favorites";
saveText.setAttribute("onclick", `saveFavorite('${result.url}')`);
} else {
saveText.textContent = "Remove Favorite";
saveText.setAttribute("onclick", `removeFavorite('${result.url}')`);
}
// Card Text
const cardText = document.createElement("p");
cardText.textContent = result.explanation;
// Footer Conatiner
const footer = document.createElement("small");
footer.classList.add("text-muted");
// Date
const date = document.createElement("strong");
date.textContent = result.date;
// Copyright
const copyrightResult =
result.copyright === undefined ? "" : result.copyright;
const copyright = document.createElement("span");
copyright.textContent = ` ${copyrightResult}`;
// Append everything together
footer.append(date, copyright);
cardBody.append(cardTitle, saveText, cardText, footer); //hide to make image display
link.appendChild(image);
card.append(link); // hide cardBody
// Append to image container
imagesContainer.appendChild(card);
});
}
// Update the DOM
function updateDOM(page) {
// Get favorites from local storage
if (localStorage.getItem("nasaFavorites")) {
favorites = JSON.parse(localStorage.getItem("nasaFavorites"));
}
imagesContainer.textContent = "";
createDOMNodes(page);
showContent(page);
}
// Get 10 images from NASA API
async function getNasaPictures() {
// Show Loader
loader.classList.remove("hidden");
try {
const response = await fetch(apiUrl);
resultsArray = await response.json();
updateDOM("results");
} catch (error) {
// Catch Error Here
}
}
// Add result to favorites
function saveFavorite(itemUrl) {
// Loop through the results array to select favorite
resultsArray.forEach((item) => {
if (item.url.includes(itemUrl) && !favorites[itemUrl]) {
favorites[itemUrl] = item;
// Show save confirmation for 2 seconds
saveConfirmed.hidden = false;
setTimeout(() => {
saveConfirmed.hidden = true;
}, 2000);
// Set Favorites in Local Storage
localStorage.setItem("nasaFavorites", JSON.stringify(favorites));
}
});
}
// Remove item from favorites
function removeFavorite(itemUrl) {
if (favorites[itemUrl]) {
delete favorites[itemUrl];
localStorage.setItem("nasaFavorites", JSON.stringify(favorites));
updateDOM("favorites");
}
}
// On Load
getNasaPictures();
.container {
display: grid;
grid-template-columns: 1fr;
grid-template-rows: 3% 1fr 0.1fr;
gap: 0px 0px;
grid-auto-flow: row;
grid-template-areas:
"header"
"content"
}
.hero {
grid-area: hero;
background-color: blue;
}
.content {
grid-area: content;
background-color: orange;
align-self: center;
justify-self: center;
}
html {
box-sizing: border-box;
}
body {
margin: 0;
background: whitesmoke;
overflow-x: hidden;
font-family: Verdana, sans-serif;
font-size: 1rem;
line-height: 1.8rem;
}
.loader {
position: fixed;
z-index: 40;
background: whitesmoke;
height: 100vh;
width: 100vw;
display: flex;
justify-content: center;
align-items: center;
}
/* Navigation */
.navigation-container {
position: fixed;
top: 0;
}
.navigation-items {
display: flex;
justify-content: center;
}
.background {
background: whitesmoke;
position: fixed;
right: 0;
width: 100%;
height: 60px;
z-index: -1;
}
.clickable {
color: #0b3d91;
cursor: pointer;
user-select: none;
}
.clickable:hover {
color: #fc3d21;
}
/* Images Container */
.images-container {
display: grid;
grid-template-columns: repeat(3, 1fr);
}
.card {
margin: 10px 10px 10px;
width: 300px;
height: 300px;
}
.card-img-top {
width: 300px;
height: 300px;
}
.card-body {
padding: 20px;
}
.card-title {
margin: 10px auto;
font-size: 24px;
}
/* Save Confirmation */
.save-confirmed {
background: white;
padding: 8px 16px;
border-radius: 5px;
box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.2);
transition: 0.3s;
position: fixed;
bottom: 25px;
right: 50px;
z-index: 500;
}
/* Hidden */
.hidden {
display: none;
}
.brand {
float: right;
}
.fave {
margin-right: 50%;
}
#myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
/* #myImg:hover {opacity: 0.7;} */
/* The Modal (background) */
.modal {
display: none;
/* Hidden by default */
position: fixed;
/* Stay in place */
z-index: 1;
/* Sit on top */
padding-top: 100px;
/* Location of the box */
left: 0;
top: 0;
width: 100%;
/* Full width */
height: 100%;
/* Full height */
overflow: auto;
/* Enable scroll if needed */
background-color: rgb(0, 0, 0);
/* Fallback color */
background-color: rgba(0, 0, 0, 0.9);
/* Black w/ opacity */
}
/* Modal Content (image) */
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
/* Caption of Modal Image */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}
/* The Close Button */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
/* 100% Image Width on Smaller Screens */
#media only screen and (max-width: 700px) {
.modal-content {
width: 100%;
}
}
<!-- Loader -->
<div class="loader hidden">
<img src="rocket.svg" alt="Rocket Icon" />
</div>
<!-- Container -->
<div class="container">
<div class="header">
<div class="navigation-container">
<span class="background"></span>
<!-- Results Nav -->
<span class="navigation-items" id="resultsNav">
</span>
<!-- Favorites Nav -->
<span class="navigation-items hidden" id="favoritesNav">
</span>
</div>
</div>
<div class="content">
<div class="container-fluid">
<div class="row">
<div class="column">
<div id="myImg" alt="Snow" class="images-container"></div>
</div>
</div>
</div>
</div>
<!-- The Modal -->
<div id="myModal" class="modal">
<span class="close">×</span>
<img class="modal-content" id="img01">
<div id="caption"></div>
</div>
</div>
In your img.onclick function/event listener (at line 51 of your JS), your this points to the parent instead of the image itself.
For a quick fix, try replacing your this with event.target (Basically, event.target.src in place of this.src and event.target.alt in place of this.alt at lines 56 and 57 of your current JS Fiddle)

Loop through elements by class name, click any element within the array, but only affect the element clicked?

I am working on a WordPress site and I have a snippet of html that iterates with repeating classes.
I am attempting to create a click function but only affect the element that is clicked. All in JavaScript.
As of right now my function is affecting all elements with the class name. Test code can be found at my CodePen or below.
I can accomplish this without nested loops as seen here. So my assumption is the problem lies within the second forEach loop. I would appreciate any light on the matter.
Thank you in advance.
/**
*Constructors
**/
const carousel = document.getElementsByClassName("carousel");
const btns = document.getElementsByClassName("btns");
/**
*Execute
**/
Array.from(btns).forEach((i) => {
i.addEventListener("click", (e) => {
Array.from(carousel).forEach((n) => {
if (i.classList.contains("slide-left")) {
n.scrollLeft -= 20;
} else if (i.classList.contains("slide-right")) {
n.scrollLeft += 20;
} else {
alert("ut oh");
}
});
});
});
/*
**Utilities
*/
/*containers*/
.feed-container {
position: absolute;
height: 200px;
width: 100%;
display: grid;
grid-template-columns: 1;
grid-template-rows: 1;
}
.carousel {
grid-row: 1;
grid-column: 1/5;
display: grid;
grid-template-columns: repeat(4, 1fr);
grid-template-rows: 1;
grid-gap: 15px;
align-self: center;
border: 1px solid #ccc;
overflow-x: scroll;
overflow-y: hidden;
}
/*div-buttons*/
div[class*="slide-"] {
/*opacity: 0;*/
position: sticky;
grid-row: 1;
z-index: 5;
place-self: center;
transition: 0.5s;
padding: 15px;
}
.slide-left {
grid-column: 1;
}
.slide-right {
grid-column: 4;
}
/*items*/
div[class*="item-"] {
grid-row: 1;
width: 400px;
height: 200px;
}
.item-1 {
background: blue;
}
.item-2 {
background: red;
}
.item-3 {
background: grey;
}
.item-4 {
background: yellow;
}
/*scrollbar*/
::-webkit-scrollbar {
display: none;
}
/*chevrons*/
[class*="chevron-"] {
box-sizing: border-box;
position: relative;
display: block;
transform: scale(var(--ggs, 1));
width: 22px;
height: 22px;
border: 2px solid transparent;
border-radius: 25px;
}
[class*="chevron-"]::after {
content: "";
display: block;
box-sizing: border-box;
position: absolute;
width: 40px;
height: 40px;
border-bottom: 8px solid;
border-left: 8px solid;
bottom: 0;
}
.chevron-left::after {
transform: rotate(45deg);
left: 15px;
}
.chevron-right::after {
transform: rotate(-135deg);
right: 15px;
}
/*
**Exceptions
*/
.btns:hover {
cursor: pointer;
}
.opaque {
opacity: 1 !important;
}
.show {
display: block;
}
<div id="wrapper" style="display:grid; grid-template-rows:repeat(2, auto); grid-gap: 100px;">
<div>
<h1>Header</h1>
<div class="feed-container">
<div class="carousel">
<div class="item-1"></div>
<div class="item-2"></div>
<div class="item-3"></div>
<div class="item-4"></div>
</div>
<div class="slide-left btns">
<div class="chevron-left"></div>
</div>
<div class="slide-right btns">
<div class="chevron-right"></div>
</div>
</div>
</div>
<br>
<div>
<h1>Header</h1>
<div class="feed-container">
<div class="carousel">
<div class="item-1"></div>
<div class="item-2"></div>
<div class="item-3"></div>
<div class="item-4"></div>
</div>
<div class="slide-left btns">
<div class="chevron-left"></div>
</div>
<div class="slide-right btns">
<div class="chevron-right"></div>
</div>
</div>
</div>
</div>
It's because you're getting all the elements with class name carousel and then looping through them with each click.
const carousel = document.getElementsByClassName("carousel");
Instead what you need to do is get the carousels only under the button's parent when you trigger the click event
eg something like this:
Array.from(btns).forEach((i) => {
i.addEventListener("click", (e) => {
const targetElement = e?.target || e?.srcElement;
const parent = targetElement.parentElement();
const carousel = Array.from(parent.getElementsByClassName("carousel"));
carousel.forEach((n) => {
if (i.classList.contains("slide-left")) {
n.scrollLeft -= 20;
} else if (i.classList.contains("slide-right")) {
n.scrollLeft += 20;
} else {
alert("ut oh");
}
});
});
});
I took a look at the following as recommend and it seems to do the trick.
I created a variable that calls the parentNode "forEach()" button clicked. Oppose to looping through each element.
Working example, codePen
const carousel = document.querySelectorAll(".carousel");
const btns = document.querySelectorAll(".btns");
btns.forEach((i) => {
i.addEventListener("click", () => {
var x = i.parentNode;
var y = Array.from(x.querySelectorAll(".carousel"));
y.forEach((n) => {
if (i.classList.contains("slide-left")) {
n.scrollLeft -= 20;
} else {
n.scrollLeft += 20;
}
});
});
});

Hover on image to add overlay in JavaScript

If I have more than one image in a div wrapper. I want to add overlay on image when user hover over the image. I am trying to do using code shown below.
for(var i=0; i<document.getElementsByTagName('img').length; i++) {
document.getElementsByTagName('img')[i].addEventListener('mouseover', function(event){
let elementExists = document.getElementById('wrapper');
let Center = document.createElement('div');
let Text = document.createElement('div');
if (!elementExists) {
let Wrapper = document.createElement('div');
let parentElement = event.currentTarget.parentElement;
Wrapper.classList.add('Wrapper');
Wrapper.id = 'wrapper';
Center.classList.add('Center');
Text.innerHTML = "Sample text";
parentElement.appendChild(Wrapper);
Wrapper.appendChild(Center);
Center.appendChild(Text);
Wrapper.addEventListener('mouseout', function(event){
if (document.getElementById('wrapper')) {
document.getElementById('wrapper').remove();
}
});
}
});
}
.col-md-6 {
width: 375px;
height: 211px;
margin: 20px;
position: relative;
}
.Wrapper {
display: table;
position: absolute;
background-color: rgba(0, 0, 0, 0.5);
height: 100% !important;
width: 100%;
text-align: center;
z-index: 1000;
font-family: arial;
color: #fff;
top: 0;
}
.Center {
display: table-cell;
vertical-align: middle;
}
<div class="col-md-6">
<a href="#">
<img src="https://www.blog.google/static/blog/images/google-200x200.7714256da16f.png" />
</a>
<a href="#">
<img src="https://www.blog.google/static/blog/images/google-200x200.7714256da16f.png" />
</a>
</div>
Every time I hover on first image, code just works fine. But when I hover on 2nd image it adds overlay on 1st image only.(It should add overlay on second image) I tried to debug the code and let parentElement = event.currentTarget.parentElement; is showing the a href only.
NOTE: I came to know its because I am giving position: absolute to Wrapper. I only want to make changes in JavaScript file and at max to css.
Please let me know if you found error in the code.
It's simply a css problem. Just add this to what you currently have:
a {
position: relative;
display: inline-block;
}
.Wrapper {
display: inline-block;
left: 0;
}
.Center {
display: flex;
justify-content: center;
flex-direction: column;
text-align: center;
height: 100%;
}
Also I removed the final Text div and added its text to the Center div, as it triggered the mouseout event and made it flicker.
for(var i=0; i<document.getElementsByTagName('img').length; i++) {
document.getElementsByTagName('img')[i].addEventListener('mouseover', function(event){
let elementExists = document.getElementById('wrapper');
let Center = document.createElement('div');
if (!elementExists) {
let Wrapper = document.createElement('div');
let parentElement = event.currentTarget.parentElement;
Wrapper.classList.add('Wrapper');
Wrapper.id = 'wrapper';
Center.classList.add('Center');
Center.innerHTML = "Sample text";
parentElement.appendChild(Wrapper);
Wrapper.appendChild(Center);
Wrapper.addEventListener('mouseout', function(event){
if (document.getElementById('wrapper')) {
document.getElementById('wrapper').remove();
}
});
}
});
}
.col-md-6 {
width: 375px;
height: 211px;
margin: 20px;
position: relative;
}
a {
position: relative;
display: inline-block;
}
.Wrapper {
display: inline-block;
left: 0;
position: absolute;
background-color: rgba(0, 0, 0, 0.5);
height: 100% !important;
width: 100%;
text-align: center;
z-index: 1000;
font-family: arial;
color: #fff;
top: 0;
}
.Center {
display: flex;
justify-content: center;
flex-direction: column;
text-align: center;
height: 100%;
}
<div class="col-md-6">
<a href="#">
<img src="https://www.blog.google/static/blog/images/google-200x200.7714256da16f.png" />
</a>
<a href="#">
<img src="https://www.blog.google/static/blog/images/google-200x200.7714256da16f.png" />
</a>
</div>

Resize a div to largest possible square in container [duplicate]

This question already has an answer here:
CSS square with dynamic height
(1 answer)
Closed 5 years ago.
How can I resize a div to be the largest possible square within its container using CSS? If it is not possible with CSS, how can it be done with JavaScript?
If the container has height > width I would like the size of the square to width x width. If the container has width > height I would like the size the square to be height x height.
When the dimensions of the container changes the dimensions of the child should adjust accordingly.
I found this answer to be helpful to maintain the aspect ratio of the child. This approach doesn't work when the width of the container is larger than the height as the child overflows the parent as demonstrated in the following snippet.
.flex {
display: flex;
}
.wide,
.tall {
flex: none;
border: 3px solid red;
}
.wide {
width: 150px;
height: 100px;
}
.tall {
width: 100px;
height: 150px;
}
div.stretchy-wrapper {
width: 100%;
padding-bottom: 100%;
position: relative;
background: blue;
}
div.stretchy-wrapper>div {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
color: white;
font-size: 24px;
text-align: center;
}
<div class="flex">
<div class="wide">
<div class="stretchy-wrapper">
<div>Wide container</div>
</div>
</div>
<div class="tall">
<div class="stretchy-wrapper">
<div>Tall container</div>
</div>
</div>
</div>
Get width and height of all .stretchy-wrapper and parent of the same using map().
Now using a for loop assign max value to it parent.
Then $(window).resize call resizeDiv function whenever browser window size changes.
$(document).ready (function () {
function resizeDiv () {
var stretchyWrapper = $(".stretchy-wrapper"),
sWrapperWidth = stretchyWrapper.map (function () {
return $(this).width ();
}),
sWrapperHeight = stretchyWrapper.map (function () {
return $(this).height ();
}),
container = stretchyWrapper.map (function () {
return $(this).parent ();
});
for (var i in container) {
var maxVal = Math.max (sWrapperWidth[i], sWrapperHeight[i]);
$(container[i]).css ({"width": maxVal, "height": maxVal});
}
}
resizeDiv ();
$(window).resize (function () {
resizeDiv ();
});
});
.flex {
display: flex;
}
.wide,
.tall {
flex: none;
border: 3px solid red;
}
.wide {
width: 150px;
height: 100px;
}
.tall {
width: 100px;
height: 150px;
}
div.stretchy-wrapper {
width: 100%;
padding-bottom: 100%;
position: relative;
background: blue;
}
div.stretchy-wrapper>div {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
color: white;
font-size: 24px;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="flex">
<div class="wide">
<div class="stretchy-wrapper">
<div>Wide container</div>
</div>
</div>
<div class="tall">
<div class="stretchy-wrapper">
<div>Tall container</div>
</div>
</div>
</div>

Categories