I don't know if this question has been asked before or not. But...
I have the following JavaScript code in my HTML file:
<img id="imageDisplay">
<script type="text/javascript">
var displayImage = document.querySelector( '#imageDisplay' );
var imageArray = [ 'http://www.joongcho.com/Images/30th-Bday-Party-01.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-02.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-03.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-04.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-05.jpg',
'http://www.joongcho.com/Images/30th-Bday-Party-06.jpg' ];
var imageCount = 0;
var imageLength = imageArray.length;
displayImage.setAttribute( 'src', imageArray[ imageCount ] );
function nextImage(imageCount) {
}
function previousImage(imageCount) {
}
</script>
I'm trying to put a next Image and a previous Image function for this HTML.
For the next image, if there are more than 1 images and the image is not the last image, then there should be a link that allows a user to click through the array forwards. Also, if the image is the last image in the array, then the link is hidden.
For the previous image, if the image is not the first image of the array, then there should be a link that allows a user click through the array backwards. if the image is the first image, then the previous link should be hidden.
Any help is appreciated.
You have to attach event listeners to buttons or links (I used buttons):
var displayImage = document.getElementById('imageDisplay');
var buttonPrev = document.getElementById('button-prev');
var buttonNext = document.getElementById('button-next');
var imageArray = [ '../Images/30th-Bday-Party-01.jpg',
'../Images/30th-Bday-Party-02.jpg',
'../Images/30th-Bday-Party-03.jpg',
'../Images/30th-Bday-Party-04.jpg',
'../Images/30th-Bday-Party-05.jpg',
'../Images/30th-Bday-Party-06.jpg' ];
var imageCount = 0;
var imageLength = imageArray.length;
function nextImage () {
imageCount++;
if (imageCount >= imageLength - 1) {
buttonNext.style.display = 'none';
imageCount = imageLength - 1;
}
if (imageCount < imageLength) {
displayImage.setAttribute('src', imageArray[imageCount]);
}
if (imageCount > 0) {
buttonPrev.style.display = 'inline';
}
}
function previousImage () {
imageCount--;
if (imageCount <= 0) {
buttonPrev.style.display = 'none';
imageCount = 0;
}
if (imageCount >= 0) {
displayImage.setAttribute('src', imageArray[imageCount]);
}
if (imageCount < imageLength) {
buttonNext.style.display = 'inline';
}
}
displayImage.setAttribute('src', imageArray[imageCount]);
displayImage.textContent = imageCount;
buttonPrev.style.display = 'none';
buttonNext.addEventListener('click', nextImage);
buttonPrev.addEventListener('click', previousImage);
<img id="imageDisplay" />
<button id="button-prev">Back</button>
<button id="button-next">Forward</button>
Of course, you can't look at the images yet.
Related
let left = document.querySelector('.left');
let right = document.querySelector('.right');
let img = document.querySelector('.imgs');
let imgs = document.querySelectorAll('img');
let index = 0;
function rightimg() {
right.addEventListener('click', function () {
index++;
if (index > imgs.length - 1) {
index = 0;
}
img.style.transform = `translateX(${-index * 500}px)`;
console.log(img);
});
}
// setInterval(rightimg, 2000);
left.addEventListener('click', function () {
index--;
if (index < 0) {
index = imgs.length - 1;
}
img.style.transform = `translateX(${-index * 500}px)`;
console.log(img);
});
Hi friends,
I want to make autoplay image in this slider but setInterval is not working,
can you say what is wrong in here?
Thank you
Your function adds an eventlistener but it will only work when there will be an event(which is click in this case)
You can use swiperjs, it has many types of features and framework/library implentations. https://swiperjs.com/swiper-api
I have a div with an id of "imgArea" and I am trying to use JS to change the background image every 3 seconds. Below is the JS. No images are being displayed. What am I missing. Thank you.
imgArea = document.getElementById("picArea");
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Garmisch-Partenkirchen.JPG/1200px-Garmisch-Partenkirchen.JPG", "https://www.reisenaktuell.com/.imaging/mte/atlas-theme/atlas-gallery/dam/hotels/eigenanreisen/v/hotel-vier-jahreszeiten-garmisch-partenkirchen/bilder/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg/jcr:content/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg", "https://www.alpenferienwohnungen.de/assets/images/a/Garmisch-Partenkirchen-08-6335188a.jpg", "http://www.garmisch-partenkirchen-info.de/header/garmisch-partenkirchen.jpg" ];
var currentImage = 0;
function changeImage() {
currentImage++;
if (currentImage > images.length - 1) {
currentImage = 0;
}
imgArea.style.backgroundImage = "url(" + images[currentImage] + ")";
}
The div and code can be seen at this codepen:
https://codepen.io/centem/pen/rdjrLy
Please use this fiddle
imgArea = document.getElementById("picArea");
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Garmisch-Partenkirchen.JPG/1200px-Garmisch-Partenkirchen.JPG", "https://www.reisenaktuell.com/.imaging/mte/atlas-theme/atlas-gallery/dam/hotels/eigenanreisen/v/hotel-vier-jahreszeiten-garmisch-partenkirchen/bilder/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg/jcr:content/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg", "https://www.alpenferienwohnungen.de/assets/images/a/Garmisch-Partenkirchen-08-6335188a.jpg", "http://www.garmisch-partenkirchen-info.de/header/garmisch-partenkirchen.jpg" ];
var currentImage = 0;
function changeImage() {
currentImage++;
if (currentImage > images.length - 1) {
currentImage = 0;
}
imgArea.style.backgroundImage = "url(' "+ images[currentImage] + "')";
}
setInterval(function(){
changeImage();
}, 3000);
#picArea{
width:500px;
height:500px;
}
<div id="picArea" ></div>
<div id="imgArea" style="min-width:50px;min-height:50px;"></div>
imgArea = document.getElementById("imgArea");
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Garmisch-Partenkirchen.JPG/1200px-Garmisch-Partenkirchen.JPG", "https://www.reisenaktuell.com/.imaging/mte/atlas-theme/atlas-gallery/dam/hotels/eigenanreisen/v/hotel-vier-jahreszeiten-garmisch-partenkirchen/bilder/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg/jcr:content/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg", "https://www.alpenferienwohnungen.de/assets/images/a/Garmisch-Partenkirchen-08-6335188a.jpg", "http://www.garmisch-partenkirchen-info.de/header/garmisch-partenkirchen.jpg" ];
var currentImage = 0;
function changeImage() {
currentImage++;
if (currentImage > images.length - 1) {
currentImage = 0;
}
imgArea.style.backgroundImage = "url(" + images[currentImage] + ")";
}
//call first time
changeImage();
setInterval(changeImage, 3000);
<div id="imgArea" style="min-width:500px;min-height:500px;"></div>
Firstly the selector is wrong, you selected 'picArea' while your element name is 'imgArea' and then also you are not calling the function, you only declared it.
You should call changeImage()
imgArea = document.getElementById("picArea");
var images = [
"https://upload.wikimedia.org/wikipedia/commons/thumb/4/47/Garmisch-Partenkirchen.JPG/1200px-Garmisch-Partenkirchen.JPG", "https://www.reisenaktuell.com/.imaging/mte/atlas-theme/atlas-gallery/dam/hotels/eigenanreisen/v/hotel-vier-jahreszeiten-garmisch-partenkirchen/bilder/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg/jcr:content/vier-jahreszeiten-garmisch-partenkirchen-grainau-fotolia.jpg", "https://www.alpenferienwohnungen.de/assets/images/a/Garmisch-Partenkirchen-08-6335188a.jpg", "http://www.garmisch-partenkirchen-info.de/header/garmisch-partenkirchen.jpg" ];
var currentImage = 0;
function changeImage() {
currentImage++;
if (currentImage > images.length - 1) {
currentImage = 0;
}
imgArea = document.getElementById("#urid");
}
I have a big problem with images in javascript embedded aplications. I want make a preload image but I don't know how the browser works.
See this simple example: code
var colors = [
"http://www.robolaranja.com.br/wp-content/uploads/2014/10/Primeira-imagem-do-filme-de-Angry-Birds-%C3%A9-revelada-2.jpg",
"http://imguol.com/c/noticias/2013/12/13/13dez2013---esta-imagem-mostra-a-nebulosa-de-caranguejo-um-iconico-remanescente-de-supernova-na-nossa-galaxia-vista-do-observatorio-espacial-herschel-e-do-telescopio-hubble-uma-nuvem-de-gas-e-poeira-1386961235961_956x500.jpg",
"http://wallpaper.ultradownloads.com.br/121350_Papel-de-Parede-Imagem-Abstrata_1920x1200.jpg"
]
var currentDiv = "div2";
var count = 0;
var lenght = colors.length;
var timeForNextImage = 0;
var preloadOk = false;
setInterval(function() {
count ++;
if (count > lenght) count = 0;
var date = new Date();
var time = date.getTime();
if (time > (timeForNextImage - 3000) && preloadOk == false) {
preLoad();
} else if (time > timeForNextImage) {
play();
}
}, 300);
var play = function() {
if (currentDiv == "div2") {
$('#'+currentDiv).css("visibility", "visible");
} else {
$('#div2').css("visibility", "hidden");
}
var date = new Date();
timeForNextImage = date.getTime() + 10000;
preloadOk = false;
$("#lbl").text("div atual: "+currentDiv);
};
var preLoad = function() {
if (currentDiv == "div1") {
currentDiv = "div2";
} else {
currentDiv = "div1";
}
$("#" + currentDiv).css("background-image", 'url('+colors[count]+')');
preloadOk = true;
};
How you can look, I do a preload, in theory.. but, the browser only processes my image when I put it in the stage ?
What if I change the z-index attribute, it renders again?
You return preloadOK = true but the image doesn't load. That's not a preloader.
To make a preloader you can play with new Image() object or with load() event.
var images = new Array()
function preload() {
for (i = 0; i < preload.arguments.length; i++) {
images[i] = new Image()
images[i].src = preload.arguments[i]
}
}
preload(
"http://domain.tld/gallery/image-001.jpg",
"http://domain.tld/gallery/image-002.jpg",
"http://domain.tld/gallery/image-003.jpg"
)
See more
3 Ways to Preload Images with CSS, JavaScript, or Ajax
A simple way to preload an image is to just create an image tag and set the url as the src. You don't have to attach it to the DOM to make the request.
var preLoad = function() {
var img = new Image();
img.src = colors[count];
};
I just started learning Javascript by doing a simple card game and I'm stucked at a problem. I want to show four cards as an image before a user can select a trump by a popup box. But, everytime I run the code the cards images get displayed AFTER the popup box and not before. Please have a look at the relevant code:
function preloadImages() {
var imgs = [];
for (var i = 0; i < max_length_deck; i++) {
imgs[i] = new Image();
imgs[i].src = 'img/' + deck[i] + '.png';
}
}
function generateDeck() {
for (i = 0; i < colour.length; i++) {
for (x = 0; x < number.length; x++) {
deck.push(colour[i] + '' + number[x]);
}
}
}
function shuffleCards() {
cards.length = 0;
for (i = 0; i < max_length_deck; i++) {
var random = Math.floor(Math.random() * deck.length);
cards.push(deck[random]);
deck.splice(random, 1);
}
}
function dealCards() {
generateDeck();
preloadImages();
shuffleCards();
for (var i = 0; i < 4; i++) {
window.document.images[i].src = 'img/' + cards[i] + '.png'; //I defined four image tags at html file
}
selectTrump();
}
function selectTrump() {
var result = false;
while (result != true) {
trump = prompt("Please enter trump:", "");
result = checkTrump(trump);
}
}
I searched and tried several things already (jQuery load handlers; window.setTimeout), but nothing worked and I don't get problem. So, thank you very much for any hint!
BR
Kjaer
In the function Dealcards() you probably have to wait for the images to be loaded first, before dealing the cards. You can use add an eventhandler for this:
<html>
<head>
<script>
function loadImage()
{
alert("Image is loaded");
}
</script>
</head>
<body>
<img src="w3javascript.gif" onload="loadImage()" id="myImage">
</body>
</html>
//Or use:
// example
function addEvent(element, evnt, funct){
if (element.attachEvent)
return element.attachEvent('on'+evnt, funct);
else
return element.addEventListener(evnt, funct, false);
}
addEvent(
document.getElementById('myImage'),
'load',
function () { alert('image loaded!'); }
);
addEventListener vs onclick
i would like to make image slideshow.
First, i would have just thumbnails and when clicked on the one, it would pop up overlay(some sort of div, or something) and there would be option to move through the images. I don't want to use anykind of libraries
i have this, so far:
NewImg = new Array (
"img/1gif",
"img/2gif",
"img/3gif"
);
var ImgNum = 0;
var ImgLength = NewImg.length - 1;
var delay = 3000;
var lock = false;
var run;
function chgImg(direction) {
if (document.images) {
ImgNum = ImgNum + direction;
if (ImgNum > ImgLength) {
ImgNum = 0;
}
if (ImgNum < 0) {
ImgNum = ImgLength;
}
document.slideshow.src = NewImg[ImgNum];
}
}
function auto() {
if (lock == true) {
lock = false;
window.clearInterval(run);
}
else if (lock == false) {
lock = true;
run = setInterval("chgImg(1)", delay);
}
html part
Previous
Auto/Stop
Next
this is the regular image gallery. With regular sized images.
I don't know how to implement those thumbnails
thank for helping me around here
i forgot, i have
used following code for overlays(but don't know how to implement it here)
function toggleLayer( whichLayer )
{
var elem, vis;
if( document.getElementById )
{
elem = document.getElementById( whichLayer );
}
vis = elem.style;
if(vis.display==''&&elem.offsetWidth!=undefined&&elem.offsetHeight!=undefined)
vis.display = (elem.offsetWidth!=0&&elem.offsetHeight!=0)?'block':'none';
vis.display = (vis.display==''||vis.display=='block')?'none':'block';
}
http://jsfiddle.net/sevdah/z7Ggx/1/ on jsfiddle, but it is not working, don't know why