I am building a website, and I need to 'implement' a gallery on a group of photos. Since I'm using Spring MVC, my images are with 'img src..' tag and regular js and jquery addons don't work. Is there any plugin/library that can help me do this? If not, suggestions for making my way around it are also welcome. Here is the html, if it can somehow help.
<div id="img-slider">
<img class="slider-img" src="/LBProperties/img/bisc.jpg"/>
<img class="slider-img" src="/LBProperties/img/bisc1.jpg"/>
</div>
Thank you !
You can hide all of the images with CSS:
img {
width: 100px;
height: 100px;
display: none;
}
Get handlers to the images:
var slider = document.querySelector('#img-slider');
var images = slider.getElementsByTagName('img');
Set an index to 0:
var index = 0;
Then show the first image:
images[index].style.display = 'block';
Add a button to your HTML:
<div>
<button id="next">Next</button>
</div>
Get it with script and add a click handler:
var button = document.querySelector('#next');
button.addEventListener('click', function() {
for (var ix = 0; ix < images.length; ix++) {
images[ix].style.display = 'none';
}
index++;
if (index >= images.length) index = 0;
images[index].style.display = 'block';
});
The click handler loops through the images and hides them, increases the index, checks to make sure the index didn't go over the number of images (reset it to 0 if it does), then shows the next image.
Putting it all together:
https://jsfiddle.net/subterrane/osszqoLe/
Related
I want the user to enter a specific number and display that many images with the help of Unsplash API, but when the function calling the API is called there is a gap of 5 seconds before images finally appear on screen, and in that gap, I want to display a gif(loader) and hide it when images are finally visible on DOM, but I am not able to achieve this, can someone help
let imgNum = document.querySelector('#num')
let btn = document.querySelector("#btn")
let output = document.querySelector("#output")
let loadImg = document.querySelector("#load") // gif image
let url = "https://source.unsplash.com/random"
loadImg.style.visibility = 'hidden';
function disLoad() {
loadImg.style.visibility = 'visible';
}
function hideLoad() {
loadImg.style.display = "hidden"
}
function displayFunc() {
disLoad()
let img = ""
for (let i = 0; i < Number(imgNum.value); i++) {
let newImg = `<img src=${url}>`
img += newImg
}
hideLoad()
output.innerHTML = img
}
btn.addEventListener("click", displayFunc)
<!-- GIF in HTML -->
<div id="num"></div>
<button id="btn">button</button>
<div id="output">
<img src="https://media.tenor.com/lwoULCdn-y4AAAAC/placeholder-text.gif" id="load">
</div>
This is because the UI and your JS run on the same thread, so you add and remove the loading gif (after your processing is complete!) without the UI showing it.
You would need to add the gif and then run your processing, as a separate function, within a setTimeout() with a timeout of 0.
Detailed answer here
I have 3 images on my page. I have assigned eventListener to check for a click, once a click has occurred on one of the images, everything else gets blurred (including the other two images).
Any help is appreciated, thanks.
function showInfo() {
const images = document.getElementsByTagName("img");
const container = document.getElementsByClassName("container");
for (let i = 0; i < images.length; i++) {
images[i].addEventListener("click", (evt) => {
// images[i].style.
})
}
}
showInfo();
You can do it using forEach(). That means if you click on each of them, it must run the command. But don't forget that this method is only possible for more than one HTML tag. (You have 3 images).
After clicking on each element, you must write a for..in loop (modern ecmascript-edition) so you can choose all of the images and apply the blur.
const images = document.querySelectorAll('img');
images.forEach(e => {
// e here means each image, no matter which one is the purpose
e.addEventListener('click', () => {
for (let i in images) {
images[i].style.filter = 'blur(8px)';
i++;
}
})
})
img {
margin-block: 10px
}
<img src="https://picsum.photos/300/200" />
<img src="https://picsum.photos/300/200" />
<img src="https://picsum.photos/300/200" />
today I decided to learn how to make sliders (carousel) , I must point out that I am pretty much new to JavaScript.
First I tried to think how I should code that myself, I had no inspiration or ideas whatsoever. (Just pointless ideas) , so I went to watch youtube in hope of "enlightment" and there were solutions, but a bit too advanced for me to understand.(and long)
After that I googled "how to make sliders" and I found something simpler on w3schools. At first, I was a bit confused, but after a while I started to understand it bit by bit, of course, not totally.
So here comes the question, can someone explain me what each line does and how it affects the others? Or if there is a better and easier method, I would love to hear it.
Here is the javascript file(followed by CSS and HTML), I only modified a few variable names to understand them better and replaced var with let or const:
let index = 1;
showDivs(index);
function plusSlide(value) {
showDivs(index += value);
}
function showDivs(value) {
let i;
let slider = document.getElementsByClassName("slides");
if (value > slider.length) {
index = 1;
}
if (value < 1) {
index = slider.length;
}
for (i = 0; i < slider.length; i++) {
slider[i].style.display = "none";
}
slider[index - 1].style.display = "block";
}
.sliders {
display: flex;
width: 400px;
height: 200px;
}
input[type="button"] {
width: 100px;
}
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<link rel="stylesheet" href="css.css" type="text/css">
</head>
<body>
<input type="button" value="Back" onclick="plusSlide(-1)">
<input type="button" value="Forward" onclick="plusSlide(+1)">
<div class="sliders">
<img src="https://via.placeholder.com/150/0000FF/FFFFFF/?text=image1" width="400" height="200" class="slides">
<img src="https://via.placeholder.com/150/FF00FF/FFFFFF/?text=image2" width="400" height="200" class="slides">
<img src="https://via.placeholder.com/150/00FFFF/FFFFFF/?text=image3" width="400" height="200" class="slides">
</div>
<script src="scripts.js"></script>
</body>
</html>
This specific approach works like this:
(Explaining in comments)
let index = 1; // Initializes index variable to point to the first element
// of your slide array we'll see later
showDivs(index);
function plusSlide(value) {
showDivs(index += value); // This function just increments your index value
// and displays the next slide
}
function showDivs(value) {
let i;
/*
You get the array of slides from the dom using the class name slides
*/
let slider = document.getElementsByClassName("slides");
if (value > slider.length) { // in case we completed a full circle, we go
//from the start again
index = 1;
}
if (value < 1) { // in case we try to go left beyond number 1, we display
// the last one ( to achieve the circular ux experience )
index = slider.length;
}
for (i = 0; i < slider.length; i++) {
slider[i].style.display = "none"; // Hides every slider
}
slider[index - 1].style.display = "block"; // Shows only our index slider
}
I don't think this is the best approach. Because every time you want to change slide, every slide from the DOM element is retrieved, and its style is changed. You change the display state of every slide in every click. In my opinion you can
use the document.getElementsByClassName("slides"); only one time outside
of the function, in a greater scope and thus make your changes.
Also I wouldn't try to iterate through every slide and hide it. I would just
nitialize every slide to have their display equal to "none" and in every showDiv
I would just hide my current index ( before the incremention) and just show next one. Like this:
const slider = document.getElementsByClassName("slides");
function showDivs(value) {
slider[index-1].style.display = "none"; // hides our current slider before
// the incremention
if (value > slider.length) {
index = 1;
}
if (value < 1) {
index = slider.length;
}
slider[index - 1].style.display = "block"; // Shows only our index slider
}
.sliders {
display: none;
width: 400px;
height: 200px;
}
I have an array of URIs that represent .png elements, e.g., "./img/diamond-red-solid-1.png".
I want to assign each element of the array "gameDeck[0], gameDeck[1], etc. to div ids in HTML. Do I need to identify the elements as = SRC.IMG?
var gameDeck[];
var gameBoardCards = function () {
for (let cardArr of cardsToLoad)
gameDeck.push("./img/" + cardArr + ".png");
}
gameBoardCards();
document.addEventListener('DOM Content Loaded', function () {
gameDeck[0] = document.getElementById("card1");
gameDeck[1] = document.getElementById("card2");
etc.
});
The way I'm understanding your question is that you would like to target the divs in your HTML with ids of card1, card2, card3... card12 etc.
You would like to insert an img tag into each of these divs with the src being the URIs of the gameDeck array.
The following code achieves this. I've tested it and it works fine. Hope it helps :)
document.addEventListener('DOMContentLoaded', function () {
//iterate through the gameDeck array.
for (let x = 0;x < gameDeck.length;x++){
//create an img tag for each gameDeck element
var imgElement = document.createElement("img");
//set the source of the img tag to be the current gameDeck element (which will be a URI of a png file)
imgElement.src = gameDeck[x];
//target the div with id "card(x + 1)"
var cardID = "card" + (x + 1);
var cardElement = document.getElementById(cardID);
//append the img tag to the card element
cardElement.appendChild(imgElement);
}
//log the HTML to the console to check it
console.log(document.getElementById('body').innerHTML);
});
Here is a way that you can either insert images as background images, or as <img /> elements into the divs you are referring to:
<div id="card0" style="width: 100px; height: 100px;"></div>
<div id="card1" style="width: 100px; height: 100px;"></div>
let loadedImage = [];
function preloadImages(urls, allImagesLoadedCallback) {
let loadedCounter = 0;
let toBeLoadedNumber = urls.length;
urls.forEach(function(url) {
preloadImage(url, function() {
loadedCounter++;
console.log(`Number of loaded images: ${loadedCounter}`);
if (loadedCounter == toBeLoadedNumber) {
allImagesLoadedCallback();
}
});
});
function preloadImage(url, anImageLoadedCallback) {
img = new Image();
img.src = url;
img.onload = anImageLoadedCallback;
loadedImage.push(img);
}
}
function gameBoardCards() {
for (let i = 0; i < loadedImage.length; i++) {
document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`;
// document.getElementById(`card${i}`).appendChild(loadedImage[i]);
}
}
preloadImages([
`https://upload.wikimedia.org/wikipedia/commons/thumb/7/7d/Color_icon_green.svg/2000px-Color_icon_green.svg.png`, `https://upload.wikimedia.org/wikipedia/commons/thumb/f/ff/Solid_blue.svg/225px-Solid_blue.svg.png`
], function() {
console.log(`all images were loaded`);
gameBoardCards();
// continue your code
});
It may seem like a bit much for what you are trying to accomplish, but I threw in a proper image-loading handler there. The preloadImages function will handle the loading of images, that way they are properly preloaded, and can render to the DOM. Often times, we try to use images before they are properly loaded, resulting in them sometimes not being displayed, despite no errors are being thrown.
The rest of the code is straight forward, in the for loop, it loops through the existing divs and you can either use the current active line document.getElementById(`card${i}`).style.backgroundImage = `url('${loadedImage[i].src}')`; to use the loadedImage[i] image src to load that as the divs's background image. Or you can use the commented-out line directly below that document.getElementById(`card${i}`).appendChild(loadedImage[i]); to insert an <img /> element into that div. Just use either one that works for you.
You can see the code in action in this JS Fiddle demo.
Hope this helps :)
So I got a site full of images and they are are all in random order, everytime you refresh the page. You have to search for a image which is always on a different place.
function randomWaldo() {
var randomNummer = Math.floor((Math.random() * 100) + 1);
document.getElementsByTagName('img')[randomNummer].src = "images/waldo.jpg";}
Now I want the first paragraph in my HTML to change when you click on that one image. How can I do this?
You can try to select the image who have the wanted source.
And add a class or id to your paragraph for readability.
document.querySelectorAll("img[src='images/waldo.jpg']")[0].onclick=function()
{
document.getElementById("paragraphid").innerHTML="You win";
};
Example
document.querySelectorAll("img[src='image/waldo.jpg']")[0].onclick=function()
{
document.getElementById("rep").innerHTML="you win !";
}
img{
height:100px;
width:100px;
}
<p id="rep"></p>
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/nok.jpg" alt="nok">
<img src="image/waldo.jpg" alt="waldo">
<img src="image/nok.jpg" alt="nok">
<script type="text/javascript" >
var images = document.getElementsByTagName('img');
//find all paragraphs
var paragraphs = document.getElementsByTagName('p');
//define function called on click
function changeParagraph() {
//change first paragraph if exists
if(paragraphs.length) {
paragraphs[0].innerHTML = 'I have been changed!';
}
}
/*
for(var i = 0; i < images.length; i++) {
//set onclick event to every image
images[i].onclick = changeParagraph;
}
*/
// set onclick to the randomImage
images[randomNumber].onclick = changeParagraph;
</script>
Assuming your first paragraph exists before the user clicks the picture, you can add an onClick element to your img tag. Try something like this, changing the URL obviously for your own picture:
<p id = "first">You haven't found Waldo
</p>
<img id = "waldo" src = https://pbs.twimg.com/profile_images/561277979855056896/4yRcS2Zo.png
onclick = "addparagraph()"
/>
JavaScript:
function addparagraph(){
document.getElementById("first").innerHTML = "you found Waldo!";
}