change position of images in an array - javascript

I am adding an image slider to my page and are trying to change the image when I click either the "left button" or "right button"
<div class="gallary">
<img class="img" src='https://images.unsplash.com/photo-1587374194137-681fd73fab43?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='0'>
<img class="img" src='https://images.unsplash.com/photo-1586283294663-b82b25f4d660?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='1'>
<img class="img" src='https://images.unsplash.com/photo-1502945015378-0e284ca1a5be?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='2'>
<img class="img" src='https://images.unsplash.com/photo-1552236867-1caaa93299e2?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='3'>
</div>
<button class="button left" >
Scroll left
</button>
<button class="button right" >
scroll right
</button>
And for my js file I have selected the left and right button and added a event listener to the left button
const btnLeft = document.querySelector(".left");
const btnRight = document.querySelector(".right");
let images = document.querySelectorAll("img");
let arr = [...images];
btnLeft.addEventListener("click", function(){
arr.push(arr.shift());
console.log(arr);
})
When I console log the array inside the function it changes order as I want to but nothing happens to my images. They stay in the same position.
Any suggestions to what I should do?

You have created a copy of images. Changing image array position, wont reflect in DOM. You need to clear dom and reconstruct it.
Suggestion: Instead of creating dom, use show hide on element based on position
const btnLeft = document.querySelector(".left");
const btnRight = document.querySelector(".right");
let images = document.querySelectorAll("img");
let arr = [...images];
const gallary = document.querySelector(".gallary");
btnLeft.addEventListener("click", function () {
gallary.innerHTML = "";
arr.push(arr.shift());
arr.forEach((dom) => {
gallary.append(dom);
});
});
<div class="gallary">
<img class="img" src='https://images.unsplash.com/photo-1587374194137-681fd73fab43?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='0'>
<img class="img" src='https://images.unsplash.com/photo-1586283294663-b82b25f4d660?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='1'>
<img class="img" src='https://images.unsplash.com/photo-1502945015378-0e284ca1a5be?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='2'>
<img class="img" src='https://images.unsplash.com/photo-1552236867-1caaa93299e2?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='3'>
</div>
<button class="button left" >
Scroll left
</button>
<button class="button right" >
scroll right
</button>
Better solution:
const btnLeft = document.querySelector(".left");
const btnRight = document.querySelector(".right");
let images = document.querySelectorAll("img");
let activeIndex = 0;
toggleImage(activeIndex);
btnLeft.addEventListener("click", function () {
activeIndex -= 1;
if (activeIndex < 0) {
activeIndex = images.length-1;
}
toggleImage(activeIndex);
});
btnRight.addEventListener("click", function () {
activeIndex += 1;
if (activeIndex >= images.length) {
activeIndex = 0;
}
toggleImage(activeIndex);
});
function toggleImage(index) {
images.forEach((img) => {
img.classList.remove("active");
img.classList.add("hide");
});
images[index].classList.remove("hide");
images[index].classList.add("active");
}
.active {
border: 1px solid;
display: block;
}
.gallary .hide {
display: none;
}
<div class="gallary">
<img class="img" src='https://images.unsplash.com/photo-1587374194137-681fd73fab43?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='0'>
<img class="img" src='https://images.unsplash.com/photo-1586283294663-b82b25f4d660?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='1'>
<img class="img" src='https://images.unsplash.com/photo-1502945015378-0e284ca1a5be?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='2'>
<img class="img" src='https://images.unsplash.com/photo-1552236867-1caaa93299e2?ixlib=rb-1.2.1&q=80&fm=jpg&crop=entropy&cs=tinysrgb&w=400&fit=max&ixid=eyJhcHBfaWQiOjE0NTg5fQ' alt='3'>
</div>
<button class="button left" >
Scroll left
</button>
<button class="button right" >
scroll right
</button>

Related

How can I add css class to the to the nested element using DOM?

I have four child divs inside the container div, every child div has a button, image, and text inside. Images have to be blurry and text has to be hidden by default.
And when the user clicks the button, the button should be hidden, image and text should become clear and visible.
I'm trying to add or remove CSS classes from elements using for loop, but that just doesn't work at all...
let btns = document.querySelectorAll(".btn");
let images = document.querySelectorAll(".img");
let imgTexts = document.querySelectorAll(".img-text");
images.forEach((el) => el.classList.add("blur"));
imgTexts.forEach((el) => el.classList.add("hidden"));
for (let i = 0; i < btns; i++) {
btns[i].addEventListener("click", function () {
btns[i].classList.add("hidden");
});
}
.blur {
filter: blur(8px);
-webkit-filter: blur(8px);
}
.hidden {
display: none;
}
<div class="container">
<div class="card">
<button class="btn">Open the Gift</button>
<img
src=""
alt="#" class="img">
<p class="img-text">CONGRATULATIONS🎉</p>
</div>
<div class="card">
<button class="btn">Open the Gift</button>
<img
src=""
alt="#" class="img">
<p class="img-text">CONGRATULATIONS🎉</p>
</div>
<div class="card">
<button class="btn">Open the Gift</button>
<img
src=""
alt="#" class="img">
<p class="img-text">CONGRATULATIONS🎉</p>
</div>
<div class="card">
<button class="btn">Open the Gift</button>
<img
src=""
alt="#" class="img">
<p class="img-text">CONGRATULATIONS🎉</p>
</div>
</div>
for (let i = 0; i < btns; i++) {
btns[i].addEventListener("click", function () {
btns[i].classList.add("hidden");
});
}
Here, in the conditions of the for loop, write "i < btns.length".
There is not a boundation that you can create only one class. You can create multiple classes and just on and add and remove the class according to your need.
example code
HTML
<img class = "image imageHidden" src = alt = >
<button class = "button buttonHidden">Click me</button>
now I created two classes at the same time I can use them to my need in javascript
CSS
.image {
visiblity: visible}
.imageHidden {
visibility: hidden}
.button {
visibility: visible}
.buttonHidden {
visibility: hidden}
now I used them in CSS that I can use in javascript
document.querySelector(".button").addEventListener("click",function () {
document.querySelector("img").classList.add("image");
document.querySelector("button").classList.add("buttonHidden");});
this code will hide the button and show the image you can use this method according to your need.

simple picture over picture in html

im trying to build a website, where u click on a text, and a picture appears, when you click on this picture, the next one appears and so on. If you reach the last picture, the first one should appear if you click on it. My code is very complicated and it does not work with the last picture. I hope somebody can help me!
<head>
<script type="text/javascript">
function showImage() {
document.getElementById('loadingimage').style.visibility="visible";
}
function showImage2() {
document.getElementById('loadingimage2').style.visibility="visible";
}
function showImage3() {
document.getElementById('loadingimage3').style.visibility="visible";
}
</script>
</head>
<body>
<a onclick="showImage()">Hier clicken</a>
<img onclick="showImage2()" id="loadingimage" src="pic/pic1.jpg" alt="" style="visibility:hidden"></img>
<img onclick="showImage3()" id="loadingimage2" src="pic/pic2.jpg" alt="" style="visibility:hidden"></img>
<img onclick="showImage4()" id="loadingimage3" src="pic/pic3.jpg" alt="" style="visibility:hidden"></img>
</body>
For simplicity, the button will be hidden after you click the first time on the button.
let start = 0,
total = 3,
hasStarted = false;
const images = [...document.querySelectorAll(".image")];
const button = document.querySelector("button");
function showImage() {
if (!hasStarted) {
button.classList.add("hide")
hasStarted = !hasStarted;
}
images.forEach(image => {
if (image.classList.contains("show")) {
image.classList.remove("show");
image.classList.add("hide");
}
})
document.querySelector(`.image${start}`).classList.add("show");
++start;
start = start % total;
}
images.forEach(image => {
image.addEventListener("click", showImage)
})
.hide {
visibility: hidden;
}
.show {
visibility: visible;
}
<button onclick="showImage()">Hier clicken</button>
<img class="image image0 hide" id="loadingimage1" src="https://source.unsplash.com/random/200x200" alt=""></img>
<img class="image image1 hide" id="loadingimage2" src="https://source.unsplash.com/random/200x200" alt=""></img>
<img class="image image2 hide" id="loadingimage3" src="https://source.unsplash.com/random/200x200" alt=""></img>
I feel this is what you need:
<head>
<script type="text/javascript">
function showImage() {
document.getElementById('loadingimage').style.visibility = "visible";
document.getElementById('loadingimage').style.position = 'absolute';
}
function showImage2() {
document.getElementById('loadingimage2').style.visibility = "visible";
document.getElementById('loadingimage2').style.zIndex = '10';
document.getElementById('loadingimage2').style.position = 'absolute'
}
function showImage3() {
document.getElementById('loadingimage3').style.visibility = "visible";
document.getElementById('loadingimage3').style.zIndex = '15';
document.getElementById('loadingimage3').style.position = 'absolute'
}
function showImage4() {
document.getElementById('loadingimage').style.zIndex = '20';
}
</script>
</head>
<body>
<a onclick="showImage()">Hier clicken</a>
<img onclick="showImage2()" id="loadingimage" src="https://source.unsplash.com/random/200x201" alt="" style="visibility:hidden">
<img onclick="showImage3()" id="loadingimage2" src="https://source.unsplash.com/random/200x202" alt="" style="visibility:hidden">
<img onclick="showImage4()" id="loadingimage3" src="https://source.unsplash.com/random/200x203" alt="" style="visibility:hidden">
</body>

Next/prev button for modal with Javascript

I have been trying to make modal for a custom site I'm building. Everything seemed to go fine. It displayed whichever picture I clicked on and "previous" button works as intended. However, there seems to be a problem with "next" button because it behaves differently depending on which picture I'm currently on. Sometimes it jumps by few indexes forward or even backwards. Some insight would be appreciated. Thanks in advance. Here is a code HTML:
<div id="modalcontainer" class="displaynone">
<h4>
<span id="close">X</span>
</h4>
<img src="" alt="" id="modalcontent">
<div class="buttoncontainer">
<div class="previous">
<span id="prev"><</span>
</div>
<div class="next">
<span id="next">></span>
</div>
</div>
</div>
<div id="imgcontainer">
<img src="images/1.JPG" alt="">
<img src="images/2.JPG" alt="">
<img src="images/3.JPG" alt="">
<img src="images/4.JPG" alt="">
<img src="images/8.png" alt="">
<img src="images/9.jpg" alt="">
<img src="images/10.jpg" alt="">
</div>
And JS:
const modalContainer = document.getElementById("modalcontainer");
const prevButton = document.getElementById("prev");
const nextButton = document.getElementById("next");
const closeModal = document.getElementById("close");
const modalContent = document.getElementById("modalcontent");
const imgContainer = document.getElementById("imgcontainer");
let containerImages = imgContainer.querySelectorAll("img");
let imgIndex = 0;
containerImages.forEach(function(img){
img.setAttribute("data-index", imgIndex++);
img.addEventListener("click", () => {
if(modalContainer.classList.contains("displaynone")){
modalContainer.classList.remove("displaynone");
modalContainer.classList.add("displaymodal");
modalContent.src = img.src;
};
imgIndex = img.dataset.index;
console.log(imgIndex);
});
});
closeModal.addEventListener("click", () => {
if(modalContainer.classList.contains("displaymodal")){
modalContainer.classList.remove("displaymodal");
modalContainer.classList.add("displaynone");
}
imgIndex = 0;
});
nextButton.addEventListener("click", () => {
imgIndex = (imgIndex += 1) % containerImages.length;
modalContent.src = containerImages[imgIndex].src;
console.log(imgIndex);
});
prevButton.addEventListener("click", () => {
imgIndex = (imgIndex -= 1);
if (imgIndex < 0) {
imgIndex = containerImages.length - 1;
console.log(imgIndex);
};
modalContent.src = containerImages[imgIndex].src;
console.log(imgIndex);
});
I dummied up some objects to get it to run and your previous/next button code seems to work. It there some other code that might be involved? Something modifying the number of images in the imageContainer?
const prevButton = document.querySelector("#prev");
const nextButton = document.querySelector("#next");
let images = document.querySelectorAll("img");
let imgIndex = 0;
images.forEach((img) =>
img.addEventListener("click", () => {
imgIndex = parseInt(img.dataset.index);
setSelected();
})
);
setSelected();
prevButton.addEventListener("click", () => {
imgIndex = imgIndex -= 1;
if (imgIndex < 0) imgIndex = images.length - 1;
setSelected();
});
nextButton.addEventListener("click", () => {
imgIndex = (imgIndex += 1) % images.length;
setSelected();
});
function setSelected() {
images.forEach((img) => img.classList.remove("selected"));
images[imgIndex].classList.add("selected");
}
img {
display: inline-block;
border: 2px solid transparent;
}
.selected {
border: 2px solid red;
}
<div id="imageContainer">
<img src="https://picsum.photos/100?random=1" data-index="0">
<img src="https://picsum.photos/100?random=2" data-index="1">
<img src="https://picsum.photos/100?random=3" data-index="2">
<img src="https://picsum.photos/100?random=4" data-index="3">
</div>
<div>
<button id="prev">Prev</button>
<button id="next">Next</button>
</div>

How can i make a different counter for each photo in js? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I'm having problems with counter in js, i've made 3 img tags with different id's, but having difficulties what to put in if statement for each counter? How can i see which photo has been clicked?
var count = 0;
function promptImg() {
var count1 = document.getElementById(test1)
var count2 = document.getElementById(test2)
var count3 = document.getElementById(test3)
}
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png">
</div>
<div class="2">
<img id="test2" onclick="promptImg()" src="gerbera.jpg">
</div>
<div class="3">
<img id="test3" onclick="promptImg()" src="gipsofila.jpg">
</div>
</div>
If you want to know how to determine which image was clicked, make sure you pass this into the function assigned to the onclick attribute.
To keep track of click frequency, you can use object or a Set to store the associated count with the ID of the image.
const counter = { };
function promptImg(img) {
counter[img.id] = (counter[img.id] || 0) + 1;
console.log(JSON.stringify(counter));
}
body div {
display: flex;
flex-direction: row;
grid-column-gap: 1em;
align-content: center;
}
.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
</div>
<div class="2">
<img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
</div>
<div class="3">
<img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
</div>
</div>
Or store the click as a data attribute using dataset.
const counter = { };
const displayClickFrequency = () =>
console.log(JSON.stringify([...document.querySelectorAll('img')]
.reduce((map, img) => ({
...map,
[img.id]: parseInt(img.dataset.clicked, 10) || 0
}), {})));
function promptImg(img) {
const previousValue = parseInt(img.dataset.clicked, 10) || 0;
img.dataset.clicked = previousValue + 1;
displayClickFrequency();
}
body div {
display: flex;
flex-direction: row;
grid-column-gap: 1em;
align-content: center;
}
.as-console-wrapper { max-height: 2.667em !important; }
<div id="flowers">
<div class="1">
<img id="test1" onclick="promptImg(this)" src="http://placekitten.com/120/60" />
</div>
<div class="2">
<img id="test2" onclick="promptImg(this)" src="http://placekitten.com/150/75" />
</div>
<div class="3">
<img id="test3" onclick="promptImg(this)" src="http://placekitten.com/160/80" />
</div>
</div>
You can do it by using an event listener and checking the id of its target element:
document.addEventListener("click", function(element) {
if (element.target.id === "test1") {
//do something
}
});
You can do that with one of there two options:
function promptImg() {
console.log(event.target);
}
[...document.querySelectorAll(".flowers-with-eventlistener img")].forEach(img => {
img.addEventListener("click", () => {
console.log(event.target)
})
})
img {
width: 100px;
height: 100px;
}
<div class="flowers-with-onclick">
<img onclick="promptImg()" src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
<img onclick="promptImg()" src="gerbera.jpg">
<img onclick="promptImg()" src="gipsofila.jpg">
</div>
<div class="flowers-with-eventlistener">
<img src="rosa-avon-crvena-ajevke-52-373-standard-1.png" >
<img src="gerbera.jpg">
<img src="gipsofila.jpg">
</div>
If you apply a class to all of the images, you can create an event listener to find out which one has been clicked.
You can test it yourself by using the snippet below and clicking the images. Hope this helped.
var images = document.querySelectorAll(".shared-class");
for (i = 0; i < images.length; i++) {
images[i].addEventListener("click", function() {
console.log(this)
})
}
<div>
<img src="#" id="test1" class="shared-class" />
<img src="#" id="test2" class="shared-class" />
<img src="#" id="test3" class="shared-class" />
</div>
You possibly wat to delegate your clicks to the container - in your case the flowers div
window.addEventListener("load", function() { // on page load
document.getElementById("flowers").addEventListener("click", function(e) { // on click in flowers
const tgt = e.target;
if (tgt.tagName === "IMG") {
console.log(tgt.id);
}
})
})
img { width: 200px; }
<div id="flowers">
<div class="1"> <img id="test1" src="https://pharmarosa.hr/galeria_ecomm/5413/rosa-avon-crvena-ajevke-52-373-standard-1.png" /> </div>
<div class="2"> <img id="test2" src="https://upload.wikimedia.org/wikipedia/commons/2/23/Azimut_Hotels_Red_Gerbera.JPG" /></div>
<div class="3"> <img id="test3" src="https://www.provenwinners.com/sites/provenwinners.com/files/imagecache/low-resolution/ifa_upload/gypsophila-festival-star-02.jpg" /> </div>
</div>
To notice when a user clicks an element (such as an image) on your webpage, you probably want to use the .addEventListener method on that element or one of its "ancestor" elements in the DOM.
Check out MDN's Event Listener page and see the verbose example in the snippet.
// Identifies some elements;
const
flowersContainer = document.getElementById("flowers"),
rosaImg = document.getElementById("rosa-img"),
gerberaImg = document.getElementById("gerbera-img"),
gipsofilaImg = document.getElementById("gipsofila-img"),
countersContainer = document.getElementById("counters");
// Calls `handleImageClicks` when the user clicks on flowersContainer
// (This "event delegation" lets us avoid adding a listener
// for each image, which matters more in larger programs)
flowersContainer.addEventListener("click", handleImageClicks);
// Defines `handleImageClicks`
function handleImageClicks(event){
// Listeners can access events, which have targets
const clickedThing = event.target;
// Calls `incrementCount` for the selected flower
if(clickedThing == rosaImg){ incrementCount("rosa"); }
else if(clickedThing == gerberaImg){ incrementCount("gerbera"); }
else if(clickedThing == gipsofilaImg){ incrementCount("gipsofila"); }
}
// Defines `incrementCount`
function incrementCount(flowerName){
const
// `.getElementsByClassName` returns a list of elements
// (even though there will be only one element in the list)
listOfMatchingElements = countersContainer.getElementsByClassName(flowerName),
myMatchingElement = listOfMatchingElements[0], // First element from list
currentString = myMatchingElement.innerHTML, // HTML values are strings
currentCount = parseInt(currentString), // Converts to number
newCount = currentCount + 1 || 1; // Adds 1 (Defaults to 1)
myMatchingElement.innerHTML = newCount; // Updates HTML
}
#flowers > div { font-size: 1.3em; padding: 10px 0; }
#flowers span{ border: 1px solid grey; }
#counters span{ font-weight: bold; }
<div id="flowers">
<div><span id="rosa-img">Picture of rosa</span></div>
<div><span id="gerbera-img">Picture of gerbera</span></div>
<div><span id="gipsofila-img">Picture of gipsofila</span></div>
</div>
<hr />
<div id=counters>
<div>User clicks on rosa: <span class="rosa"></span></div>
<div>User clicks on gerbera: <span class="gerbera"></span></div>
<div>User clicks on gipsofila: <span class="gipsofila"></span></div>
</div>
In your promptImg function if you use jquery, and you should, inside it add
var idClick=$(this).attr("id");
console.log("This link was clicked"+idClick);
and then you can easily IF it

How do I implement the scroll to top

I have written code with a click function. If the user clicks "next", set class "onscreen" to the next element.
What I want is the element that has class "onscreen" to scroll to top with animation duration of 1s.
This is my code:
HTML
<div class="slides">
<div class="slide onscreen" id="one">one</div>
<div class="slide" id="two">two</div>
<div class="slide" id="third">third</div>
<div class="slide" id="fourth">fourth</div>
</div>
<div class="buttons">
<button class="next" onclick="slide(this.className)">
Next slide
</button>
<button class="prev" onclick="slide(this.className)">
Previous slide
</button>
</div>
CSS
.buttons{
width:170px;
position:fixed;
top:10px;
left:50%;
margin-left:-85px;
}
.onscreen {
background-color: green;
}
Javascript
window.onload = function() {
var slide = document.getElementsByClassName("slide");
for (var i = 0; i < slide.length; i++) {
var heightslide = slide[i].offsetHeight;
}
console.log(heightslide);
}
var active = document.getElementsByClassName("onscreen");
function slide(prevnext) {
if (prevnext === "next") {
if (active[0].nextElementSibling) {
active[0].nextElementSibling.className = "slide onscreen";
active[0].className = "slide";
}
} else {
if (active[0].previousElementSibling) {
active[0].previousElementSibling.className = " slide onscreen ";
active[active.length - 1].className = "slide";
}
}
}
Hope somebody can help me with this.
Thanks a lot

Categories

Resources