How to display ALT text to my Lightbox gallery? - javascript

I am trying to create my own Lightbox Gallery instead of using a plugin. So I found a really simple script online but now I am trying to display the alt text of the image that is shown in the Lightbox as a caption.
I managed to display the alt text of all images in the gallery but obviously only the alt text of the shown image should be displayed, can someone help me as to how I only pick the alt text from the shown image?
Here is my code:
<div class="lightbox">
<div class="wrapper">
<div class="gallery">
<div class="image">
<div class="subimage"><img src="images/cardmapr-rDzI7m7sjPE-unsplash.jpg" loading="lazy" sizes="28vw" srcset="images/cardmapr-rDzI7m7sjPE-unsplash-p-500.jpeg 500w, images/cardmapr-rDzI7m7sjPE-unsplash-p-800.jpeg 800w, images/cardmapr-rDzI7m7sjPE-unsplash-p-1080.jpeg 1080w, images/cardmapr-rDzI7m7sjPE-unsplash-p-1600.jpeg 1600w, images/cardmapr-rDzI7m7sjPE-unsplash.jpg 1920w" alt="Caption alt test" class="image_2"></div>
</div>
<div class="image">
<div class="subimage"><img src="images/sergei-a--heLWtuAN3c-unsplash.jpg" loading="lazy" sizes="28vw" srcset="images/sergei-a--heLWtuAN3c-unsplash-p-500.jpeg 500w, images/sergei-a--heLWtuAN3c-unsplash-p-800.jpeg 800w, images/sergei-a--heLWtuAN3c-unsplash-p-1080.jpeg 1080w, images/sergei-a--heLWtuAN3c-unsplash-p-1600.jpeg 1600w, images/sergei-a--heLWtuAN3c-unsplash.jpg 1920w" alt="caption 2" class="image_2"></div>
</div>
<div class="image">
<div class="subimage"><img src="images/good-faces-agency-sKRavSCadwE-unsplash.jpg" loading="lazy" sizes="28vw" srcset="images/good-faces-agency-sKRavSCadwE-unsplash-p-500.jpeg 500w, images/good-faces-agency-sKRavSCadwE-unsplash-p-800.jpeg 800w, images/good-faces-agency-sKRavSCadwE-unsplash-p-1080.jpeg 1080w, images/good-faces-agency-sKRavSCadwE-unsplash-p-1600.jpeg 1600w, images/good-faces-agency-sKRavSCadwE-unsplash.jpg 1920w" alt="" class="image_2"></div>
</div>
<div class="image">
<div class="subimage"><img src="images/Bild_Haarentfernung_Nachher.png" loading="lazy" sizes="28vw" srcset="images/Bild_Haarentfernung_Nachher-p-500.png 500w, images/Bild_Haarentfernung_Nachher.png 536w" alt="caption last" class="image_2"></div>
</div>
</div>
</div>
<div class="preview-box">
<div class="image-box">
<div class="caption2"></div><img src="https://d3e54v103j8qbb.cloudfront.net/plugins/Basic/assets/placeholder.60f9b1840c.svg" loading="lazy" alt="test test" class="image_3">
</div>
</div>
<div class="shadow">
<div class="icon closebutton"></div>
<div class="slide prev"></div>
<div class="slide next"></div>
<div class="details">
<div class="title">
<p class="current-img">Test1</p>
<div>/</div>
<p class="total-img">Test2</p>
</div>
</div>
</div>
</div>
The very last part in this code, is the jquery I am using to display the alt texts:
const gallery = document.querySelectorAll(".image"),
previewBox = document.querySelector(".preview-box"),
previewImg = previewBox.querySelector("img"),
shadow = document.querySelector(".shadow"),
closeIcon = shadow.querySelector(".icon"),
currentImg = shadow.querySelector(".current-img"),
totalImg = shadow.querySelector(".total-img");
window.onload = ()=>{
for (let i = 0; i < gallery.length; i++) {
totalImg.textContent = gallery.length; //passing total img length to totalImg variable
let newIndex = i; //passing i value to newIndex variable
let clickedImgIndex; //creating new variable
gallery[i].onclick = () =>{
clickedImgIndex = i; //passing cliked image index to created variable (clickedImgIndex)
function preview(){
currentImg.textContent = newIndex + 1; //passing current img index to currentImg varible with adding +1
let imageURL = gallery[newIndex].querySelector("img").src; //getting user clicked img url
previewImg.src = imageURL; //passing user clicked img url in previewImg src
}
preview(); //calling above function
const prevBtn = document.querySelector(".prev");
const nextBtn = document.querySelector(".next");
if(newIndex == 0){ //if index value is equal to 0 then hide prevBtn
prevBtn.style.display = "none";
}
if(newIndex >= gallery.length - 1){ //if index value is greater and equal to gallery length by -1 then hide nextBtn
nextBtn.style.display = "none";
}
prevBtn.onclick = ()=>{
newIndex--; //decrement index
if(newIndex == 0){
preview();
prevBtn.style.display = "none";
}else{
preview();
nextBtn.style.display = "block";
}
}
nextBtn.onclick = ()=>{
newIndex++; //increment index
if(newIndex >= gallery.length - 1){
preview();
nextBtn.style.display = "none";
}else{
preview();
prevBtn.style.display = "block";
}
}
document.querySelector("body").style.overflow = "hidden";
previewBox.classList.add("show");
shadow.style.display = "block";
closeIcon.onclick = ()=>{
newIndex = clickedImgIndex; //assigning user first clicked img index to newIndex
prevBtn.style.display = "block";
nextBtn.style.display = "block";
previewBox.classList.remove("show");
shadow.style.display = "none";
document.querySelector("body").style.overflow = "scroll";
}
$('.shadow').on('click', function(e) {
if (e.target !== this)
return;
newIndex = clickedImgIndex; //assigning user first clicked img index to newIndex
prevBtn.style.display = "block";
nextBtn.style.display = "block";
previewBox.classList.remove("show");
shadow.style.display = "none";
document.querySelector("body").style.overflow = "scroll";
});
}
}
}
$('.gallery').find('img').each(function() {
var $alt = $(this).attr('alt');
$('.caption2').append($alt);
});

Related

javascript slider with thumbnail not working with both options

I make an image slider with text and thumbnail as well.
the issue is when I click the thumbnail its shows the photo correctly no issue but when I click the next button then click on the thumbnail then slider not working below is the code.
I used two arrays
for images
for text
then the next() and Previous() function to change the image when clicking on the next and previous button.
var images = ['<img src="images/1.jpg"width = 100%; height=500px; >',
'<img src="images/2.jpg"width = 100%; height=500px; >',
'<img src="images/3.jpg" width = 100%; height=500px;>'
];
var text = ["Missing From Karachi", "Missing From Peshawer", "Missing From Lahore"];
var i = 0;
var x = document.getElementById("demo");
var y = document.getElementById("text");
function next() {
i++;
if (i < images.length) {
x.innerHTML = images[i];
y.innerHTML = text[i];
} else {
i = 0;
x.innerHTML = images[i];
y.innerHTML = text[i];
}
}
function prev() {
i--;
if (i >= 0) {
x.innerHTML = images[i];
y.innerHTML = text[i];
} else {
i = images.length - 1;
x.innerHTML = images[i];
y.innerHTML = text[i];
}
}
function thumbchange(num) {
var thumb = 'images/' + num + '.jpg';
document.getElementById("demo1").src = thumb;
}
<div class="slider">
<p class="text" id="demo"><img id="demo1" src="images/1.jpg" width=100%; height=500px;> </p>
<div class="onebtn">
<button id="btn1" class="btn1 btn btn-primary btn-lg" type="button" class="prev" onclick="prev()">PREVIOUS</button>
</div>
<div class="twobtn">
<button id="btn2" class="btn2 btn btn-primary btn-lg" type="button" class="next" onclick="next()">NEXT</button>
</div>
<p id="text" class="text" style="font-size:40px; font-weight:bolder;">Missing From Karachi</p>
<br><br>
<ul class="thumbs">
<li class="img12" onclick="thumbchange(1)"><img src="images/1.jpg" width=100%;></li>
<li class="img12" onclick="thumbchange(2)"><img src="images/2.jpg"></li>
<li class="img12" onclick="thumbchange(3)"><img src="images/3.jpg"></li>
</ul>
</div>
see the example
https://codepen.io/pen/?template=WNxebOO

Random image from html on button click

I am trying to make a script that will take the images from one div element and put it to div rndmImage randomly on button click, I should see images when document is loaded, but the new div where images should go after click must be empty until click heapends. And I need only JavaScript, no jQuery, alse i can not change the html, and it has to work for any number of images. So if you have some ideas that would be great. Here's my code.
window.addEventListener('load', start, false);
function start() {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('ekran');
var pictures = document.getElementsByTagName('img');
var choose = Math.floor(Math.random()*pictures.length);
butt.addEventListener('click', menjaj, false);
function menjaj(e) {
var new = e.button;
var img = [];
for(var i = 0; i< pictures.length; i++) {
var dodaj = img[i];
img.push(dodaj);
}
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
<body>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
</body>
This is a working snippet of your code:
window.addEventListener('load', start, false);
function start () {
var butt = document.getElementsByTagName('button')[0];
var rnImg = document.getElementsByClassName('rndmImage')[0]; //Change selector to existing class and select the first (the only) one
var pictures = document.getElementsByTagName('img');
butt.addEventListener('click', menjaj, false);
function menjaj (e) {
// var new = e.button;// 'new' is reserved word in JS, you can't use it as variable name
// var btn = e.button;// but this line is useless
var choose = Math.floor(Math.random() * pictures.length); //better move this line inside this function to get rundom image every button clicks
var img = document.createElement('img'); //creates new img tag
img.src = pictures[choose].src;
rnImg.innerHTML = ''; //to delete previous image
rnImg.appendChild(img);
// var img = []; //useless lines of code
// for(var i = 0; i< pictures.length; i++) {
// var dodaj = img[i];
// img.push(dodaj);
// }
//ekran.src = 'slike/' + slike[izbor] + '.jpg';
}
}
welcome to StackOverflow!
I would first hide the .wrapper > div img as that will prevent the images to show, then, append a data-pos to help select the position and simply randomize them and pick the src to show on the placeholder
and remember that you have a <div> as placeholder, so you can't assign src, only if you change it to <img>
so, something like this 😊
function chooseImg() {
// get total images available
var totalImages = document.querySelectorAll('.wrapper > div img').length
log('totalImages', totalImages)
// get a random position
var rndPosition = Math.floor(Math.random() * totalImages)
log('rndPosition', rndPosition)
// get hold of the image for such position
var rndImage = document.querySelector('.wrapper > div img[data-pos="' + rndPosition + '"]')
log('rndImage', rndImage)
// assign the source to the DIV
document.querySelector('.rndmImage').style = 'background-image: url("' + rndImage.src + '")'
}
function log(txt, obj) {
console.log(txt, obj)
}
.wrapper > div img {
display: none;
}
.rndmImage {
background-size: contain;
background-repeat: no-repeat;
width: 100px;
height: 100px;
}
<div class="wrapper">
<div>
<img data-pos="0" src="https://randomwordgenerator.com/img/picture-generator/54e5d2434953a514f1dc8460962e33791c3ad6e04e507440742f7cd09645cc_640.jpg" alt="leto1">
<img data-pos="1" src="https://randomwordgenerator.com/img/picture-generator/54e2d1404a57a814f1dc8460962e33791c3ad6e04e5074417c2d78d19f44c4_640.jpg" alt="leto2">
<img data-pos="2" src="https://randomwordgenerator.com/img/picture-generator/57e2d5444851a414f1dc8460962e33791c3ad6e04e50744172287ad2914fc4_640.jpg" alt="leto3">
<img data-pos="3" src="https://randomwordgenerator.com/img/picture-generator/51e8d0444f56b10ff3d8992cc12c30771037dbf85254794e722c73d19245_640.jpg" alt="leto4">
<img data-pos="4" src="https://randomwordgenerator.com/img/picture-generator/53e4d2464a56a914f1dc8460962e33791c3ad6e04e507440722d7cd39345c1_640.jpg" alt="leto5">
<img data-pos="5" src="https://randomwordgenerator.com/img/picture-generator/57e9dc434b5ba414f1dc8460962e33791c3ad6e04e50744172297bd5934cc4_640.jpg" alt="leto6">
<img data-pos="6" src="https://randomwordgenerator.com/img/picture-generator/55e1dc4b4254ad14f1dc8460962e33791c3ad6e04e507440722d72d09249c7_640.jpg" alt="leto7">
<img data-pos="7" src="https://randomwordgenerator.com/img/picture-generator/57e9d4474e54a814f1dc8460962e33791c3ad6e04e50744172297cdd974cc0_640.jpg" alt="leto8">
<img data-pos="8" src="https://randomwordgenerator.com/img/picture-generator/53e6dc404951b10ff3d8992cc12c30771037dbf852547848702e7ed19348_640.jpg" alt="leto9">
</div>
<div>
<button type="button" onclick="chooseImg()">choose</button>
</div>
<div class="rndmImage"></div>
</div>
<div class="wrapper">
<img src="../Assets1/Image/1.svg" alt="" />
<img src="../Assets1/Image/2.svg" alt="" />
<img src="../Assets1/Image/3.svg" alt="" />
</div>
<button>Click</button>
<div class="randomImageContainer"></div>
const button = document.querySelector('button');
button.addEventListener('click', randomImage);
function randomImage() {
const image = document.querySelectorAll('.wrapper > img');
const randomImageContainer = document.querySelector('.randomImageContainer');
let randomNumber = Math.floor(Math.random() * image.length);
const img = document.createElement('img');
img.src = image[randomNumber].src;
randomImageContainer.appendChild(img);
}
You can do this with plain javascript like this:
document.querySelector("button").addEventListener("click", () => {
var imgElements = document.querySelectorAll(".wrapper img");
document.querySelector(".rndmImage").innerHTML = imgElements[Math.floor(Math.random() * imgElements.length)].outerHTML;
});
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
If you're able to use randojs, you can even simplify the randomness and make it all cryptographically secure like this:
document.querySelector("button").addEventListener("click", () => document.querySelector(".rndmImage").innerHTML = rando(document.querySelectorAll(".wrapper img")).value.outerHTML);
<script src="https://randojs.com/2.0.0.js"></script>
<div class="wrapper">
<div>
<img src="slike/leto1.jpg" alt="leto1">
<img src="slike/leto2.jpg" alt="leto2">
<img src="slike/leto3.jpg" alt="leto3">
<img src="slike/leto4.jpg" alt="leto4">
<img src="slike/leto5.jpg" alt="leto5">
<img src="slike/leto6.jpg" alt="leto6">
<img src="slike/leto7.jpg" alt="leto7">
<img src="slike/leto8.jpg" alt="leto8">
<img src="slike/leto9.jpg" alt="leto9">
</div>
<div>
<button type="button">choose</button>
</div>
<div class="rndmImage"></div>
</div>
Try this:
this is my image in HTML file
<snap id="image" class="btn btn-warning" onclick="changeImage()">Image</snap>
<image id="imagechange" src="https://picsum.photos/200/300" ></image>
my javascript file
imgcount = 0;
function changeImage() {
document.getElementById("imagechange").src =
"https://picsum.photos/200/" + (300 + imgcount);
imgcount++;
}
everytime you click button you get a new image

how to fix simple slider bug - javascript

I try to create a simple slider using javascipt. the problem is when counter gets to last element, It dosen't change the display to block
this is the code
<div id="slider">
<img class="slide" src="img/img13.jpg" alt=""/>
<img class="slide" src="img/img14.jpg" alt=""/>
<img class="slide" src="img/img15.jpg" alt=""/>
<img class="slide" src="img/img16.jpg" alt=""/>
<img class="slide" src="img/img17.jpg" alt=""/>
<img class="slide" src="img/img18.jpg" alt=""/>
</div>
var delay = 3000;
var i = 0;
var allSliderSlides = document.getElementsByClassName('slide');
allSliderSlides[0].style.display = "block";
setInterval(function(){
i++;
allSliderSlides[i].style.display = "block";
if(allSliderSlides[i-1].style.display=="block"){
allSliderSlides[i-1].style.display="none";
}
if(i == allSliderSlides.length-1){
i = 0;
allSliderSlides[allSliderSlides.length-1].style.display = "none";
allSliderSlides[i].style.display = "block";
}
},delay);
please give me some advice or suggestion to fix this problem
thanks
You reassigned i = 0 before your last element to become block
Try:
if(i == allSliderSlides.length-1){
allSliderSlides[allSliderSlides.length-1].style.display = "none";
allSliderSlides[i].style.display = "block";
i = 0;
}
Here's the problem:
if(i == allSliderSlides.length-1){
i = 0;
allSliderSlides[allSliderSlides.length-1].style.display = "none";
allSliderSlides[i].style.display = "block";
}
You are resetting the counter before changing the style. This results to displaying the fist image and the last image would never be displayed.
Solution: Move i = 0; to last line in the block like so:
if(i == allSliderSlides.length-1){
allSliderSlides[allSliderSlides.length-1].style.display = "none";
allSliderSlides[i].style.display = "block";
i = 0;
}
Hope that helps.

Show image ( 5 seconds then hide) , click show image ( to see next image) ?

I'm new to this. I am trying to create a HTML code which runs in HTML. It shows a image for 5 seconds and hides, next image is shown via button.
I found most of the codes via online. Can someone see where i am going wrong here.
<!DOCTYPE html>
<html>
<head>
<button id="next" onclick="showNext();">Show next image</button>
<div class="image" style="display: none;"><img src=“1.jpg”></div>
<div class="image" style="display: none;"><img src=“2.jpg”></div>
<div class="image" style="display: none;"><img src=“3.jpg”></div>
<script type="text/javascript">
var divs = document.querySelectorAll('div.image');
var button = document.getElementById('next'); //button.
var currentImage = 0;
function showNext() {
button.style.display = 'inline';
divs[currentImage].style.display = 'block';
setTimeout(hide, 5000);
}
function hide() {
button.style.display = 'block';
divs[currentImage].style.display = 'none';
currentImage = (currentImage + 1) % divs.length;
}
</script>
</head>
</html>
this is the JS that is used
var divs = document.querySelectorAll(‘image');
var button = document.getElementById('next');
var currentImage = 0;
function showNext() {
button.style.display = 'inline';
divs[currentImage].style.display = 'block';
setTimeout(hide, 500000);
}
function hide() {
button.style.display = 'block';
divs[currentImage].style.display = 'none';
currentImage = (currentImage + 1) % divs.length;
}
Updated
So, here is working code:
HTML
<button id="next">Show next image</button>
<div class="image" style="display: none;"><img src="http://dummyimage.com/100x100/000/fff.jpg"></div>
<div class="image" style="display: none;"><img src="http://dummyimage.com/100x100/990000/fff.jpg"></div>
<div class="image" style="display: none;"><img src="http://dummyimage.com/100x100/009900/fff.jpg"></div>
JS
var divs = document.querySelectorAll('.image');
var button = document.getElementById('next');
var currentImage = 0;
button.addEventListener('click', function(){
button.style.display = 'inline';
divs[currentImage].style.display = 'block';
setTimeout(hide, 2000);
});
function hide() {
button.style.display = 'block';
divs[currentImage].style.display = 'none';
currentImage = (currentImage + 1) % divs.length;
}
I provided jsfiddle too.

Image arrays with thumbnails using display property in JavaScript

I just want to upgrade image arrays using JavaScript. I added thumbnails below, So larger image can be displayed when thumbail is clicked.
The problem happens after I click "prev" or "next" (after click on the thumbail), the current image is not hidden and the next or pevious image is shown on its rigt side. Sometimes it does right, sometimes not...please help if you can. Thank you in advance.
<div id="bigImages" style="height:550px; overflow:hidden;">
<div class="image" style="display:table-cell; vertical-align:middle;"><img src="url big image 1"></div>
<div class="image" style="display:table-cell; vertical-align:middle;"><img src="url big image 2"></div>
<div class="image" style="display:table-cell; vertical-align:middle;"><img src="url big image 3"></div>
</div>
<a id="prev" href="#">Prev</a> <a id="next" href="#">Next</a>
<br/>
<div id="smallImages">
<img class ="small" src="url small image 1">
<img class ="small" src="url small image 2">
<img class ="small" src="url small image 3">
</div>
Javascript
<script type="text/javascript">
var imgArr = document.getElementById('bigImages').getElementsByTagName('img');
for(var i=1; i<imgArr.length; i++){
imgArr[i].style.display = "none";
}
i=0;
document.getElementById('prev').onclick = function(){
if(i===0){
imgArr[i].style.display = "none";
i=imgArr.length-1;
imgArr[i].style.display = "";
}
else{
imgArr[i].style.display = "none";
i--;
imgArr[i].style.display = "";
}
}
document.getElementById('next').onclick = function(){
if(i===imgArr.length-1){
imgArr[i].style.display = "none";
i=0;
imgArr[i].style.display = "";
}
else{
imgArr[i].style.display = "none";
i++;
imgArr[i].style.display = "";
}
}
function show(dptr) {
for (var i=0; i<imgArr.length; i++){
imgArr[i].style.display = 'none';
}
imgArr[dptr].style.display = "";
}
well..., I came up with this solution :
html+style
<div id="bigImages" style="height:550px; overflow:hidden;">
<div class="image" style="display:table-cell; vertical-align:middle;"><img src="http://www.livehacking.com/web/wp-content/uploads/2012/08/chrome-logo-1301044215-300x300.jpg"></div>
<div class="image" style="display:table-cell; vertical-align:middle;"><img src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Mozilla_Firefox_3.5_logo_256.png"></div>
<div class="image" style="display:table-cell; vertical-align:middle;"><img src="http://html5doctor.com/wp-content/uploads/2011/01/HTML5_Logo_256.png"></div>
</div>
<a id="prev" href="#">Prev</a> <a id="next" href="#">Next</a>
<br/>
<div id="smallImages">
<img class ="small" src="http://www.livehacking.com/web/wp-content/uploads/2012/08/chrome-logo-1301044215-300x300.jpg">
<img class ="small" src="http://upload.wikimedia.org/wikipedia/commons/e/e7/Mozilla_Firefox_3.5_logo_256.png">
<img class ="small" src="http://html5doctor.com/wp-content/uploads/2011/01/HTML5_Logo_256.png">
</div>
<style>
#smallImages img{
width:20px;
}
</style>
script
var imgArrbig = document.getElementById('bigImages').getElementsByTagName('img');
for(var i=1; i<imgArrbig.length; i++){
imgArrbig[i].style.display = "none";
}
i=0;
document.getElementById('prev').onclick = function(){
if(i===0){
imgArrbig[i].style.display = "none";
i=imgArrbig.length-1;
imgArrbig[i].style.display = "";
}
else{
imgArrbig[i].style.display = "none";
i--;
imgArrbig[i].style.display = "";
}
}
document.getElementById('next').onclick = function(){
if(i===imgArrbig.length-1){
imgArrbig[i].style.display = "none";
i=0;
imgArrbig[i].style.display = "";
}
else{
imgArrbig[i].style.display = "none";
i++;
imgArrbig[i].style.display = "";
}
}
rr = 0
$('.small').each(function(){
$(this).attr('number',''+ rr +'');
rr = rr+1
});
$('.small').click(function(i){
var compare = $(this).attr('number');
$('#bigImages img').css('display','none');
$(imgArrbig[compare]).css('display','block');
});
Here is example

Categories