I have a folder with png images and several other types of files. I only want to display the png images in the order of their names, how can I do that? All images end in a number; for example, each image is titled "image_001", "image_002", and so on. Right now I have all the images grouped together in a class as shown below but I'd prefer not to have to add every individual image if I didn't want to include any other file types. Thank you in advance.
<section>
<img class="pics" src="imgfolder/picture_001.png" style="width:80%">
<img class="pics" src="imgfolder/picture_002.png" style="width:80%">
<img class="pics" src="imgfolder/picture_003.png" style="width:80%">
</section>
<script type="text/javascript">
var index = 0;
change();
function change() {
var images = document.getElementsByClassName('pics');
for(var i = 0; i < images.length; i++) {
images[i].style.display = "none";
}
index++;
if(index > images.length) {
index = 1;
}
images[index - 1].style.display = "block";
setTimeout(change, 3000);
}
</script>
The JS code is commented with what it does. I've tested this with the same file structure that you used in your question, but you can change it on JS line 9.
<section id="img-container"></section>
const numOfPictures = 3; // The number of pictures in folder
const picturesNumberLength = 3; // "000"
let imageIndex = 1;
let imagesArray = [];
const imagesContainer = document.getElementById("img-container"); // Get the images container, has id "img-container"
for (let i = 1; i < numOfPictures + 1; i++) { // Starts at a 1 index "001"
const img = document.createElement("img"); // Create an image element
img.src = `imgfolder/picture_${(i+"").padStart(picturesNumberLength,"0")}.png`; // Set the source to "imgfolder/picture_001" or other number, works up to 999
img.classList.add("pics"); // Add the pics class
img.style.width = "80%"; // Sets width to 80%
img.style.display = "none"; // Turns off displaying it
imagesContainer.appendChild(img); // Puts the image in the image container
imagesArray.push(img); // Push the reference to the array
}
imagesArray[0].style.display = "block"; // Display the first block
setInterval(() => { // Every 3000ms (3secs), do this
imagesArray[imageIndex].style.display = "block"; // Turn displaying on
if (imageIndex > 0) imagesArray[imageIndex-1].style.display = "none"; // Turn the previous one off
else imagesArray[numOfPictures-1].style.display = "none";
imageIndex++; // Change the index
if (imageIndex >= numOfPictures) imageIndex = 0; // Go back to the beginning after going to the end
}, 3000);
Related
My goal is to display two images that last for 5 seconds each at the beginning, then images from a different folder will display for 3 seconds each. I currently display the images from the folder using set Interval and am trying to display the initial two images at the beginning using setTimeout. Right now when I run this, the page shows the code I have for the setInterval at the top of the page and the second image (fun-src) from my setTimeout blocks below. The struc-src image does not show at all. How can I align these two images with the rest of the images and make them appear only for 5 seconds and disappear after? I am new to javascript so I would appreciate any help with how to achieve this. Thank you.
<!DOCTYPE html>
<html>
<section id="img-container"></section>
<img id="Scan" struc-src="img1.png" fun-src="img2.png"/>
<script type="text/javascript">
//my attempt to display the two pictures
var scans = document.getElementById("Scan");
var strucScan = scans.getAttribute("struc-src");
var funScan = scans.getAttribute("fun-src");
scans.src = structScan;
scans.style.display = "block";
setTimeout(() => {
scans.style.display = "none";
scans.src = funcScan;
scans.style.display = "block";
}, 5000);
//everything below this line works
const numOfPictures = 200;
const picturesNumberLength = 3;
let imageIndex = 1;
let imagesArray = [];
const imagesContainer = document.getElementById("img-container");
for (let i = 1; i < numOfPictures + 1; i++) {
const img = document.createElement("img");
img.src = `foldername/homeFolder_${(i+"").padStart(picturesNumberLength,"0")}.png`;
img.classList.add("slides");
img.style.width = "80%";
img.style.display = "none";
imagesContainer.appendChild(img);
imagesArray.push(img);
}
imagesArray[0].style.display = "block";
setInterval(() => {
imagesArray[imageIndex].style.display = "block";
if (imageIndex > 0) imagesArray[imageIndex-1].style.display = "none";
else imagesArray[numOfPictures-1].style.display = "none";
imageIndex++;
if (imageIndex >= numOfPictures) imageIndex = 0;
}, 3000);
</script>
</html>
You just need an extra timeout.
0s: scans.src = structScan;
5s: scans.src = funScan;
10s: scans.style.display = "none"; imagesArray[0].style.display = "block";
var scans = document.getElementById("Scan");
var structScan = scans.getAttribute("struc-src");
var funScan = scans.getAttribute("fun-src");
scans.src = structScan;
setTimeout(() => {
scans.src = funScan;
}, 5000);
//everything below this line works
const numOfPictures = 5;
const picturesNumberLength = 3;
let imageIndex = 1;
let imagesArray = [];
const imagesContainer = document.getElementById("img-container");
for (let i = 1; i < numOfPictures + 1; i++) {
const img = document.createElement("img");
img.src = `https://via.placeholder.com/150x150&text=home${(i+"").padStart(picturesNumberLength,"0")}.png`;
img.classList.add("slides");
img.style.display = "none";
imagesContainer.appendChild(img);
imagesArray.push(img);
}
setTimeout(() => {
scans.style.display = "none";
imagesArray[0].style.display = "block";
setInterval(() => {
imagesArray[imageIndex].style.display = "block";
if (imageIndex > 0) imagesArray[imageIndex-1].style.display = "none";
else imagesArray[numOfPictures-1].style.display = "none";
imageIndex++;
if (imageIndex >= numOfPictures) imageIndex = 0;
}, 3000);
}, 10000);
<section id="img-container"></section>
<img id="Scan" struc-src="https://via.placeholder.com/150x150&text=img1.png" fun-src="https://via.placeholder.com/150x150&text=img2.png"/>
Move html outside of the script tag. You should add
<img id="Scan" struc-src="img1.png" fun-src="img2.png"/> underneath or within your section above.
var position = 0;
var size = 0;
var id = 0;
function init(){
var slides = document.getElementById("gallery").children;
var button = document.getElementById('btn');
var size = slides.length;
for(var i = 1; i<size; i++){
slides[i].style.display = 'none';
}
function slide(){
if (position < size){
slides[position].style.display = "block";
position++;
}
else{
position = 0;
for(var i=1; i<size; ++i){
slides[i].style.display = "none";
}
}
}
button.onclick =function(){
if (button.innerHTML == "PLAY") {
id = setInterval(slide, 500);
button.innerHTML = "STOP";
}
else {
button.innerHTML = "PLAY";
clearTimeout(id);
}
};
}
init();
https://fiddle.jshell.net/khimanand_oli/ytc4LeLc/3/
above is the fiddle link,
Gallery should switches slides in autorotation, or visual interval of autoration on every 0.5 second,
but currently there is more time gap when the gallery restart slides.
This is because in your slide function, when position is equal to size, you reset the list and nothing more. Just go trough it.
Display the image (last image in list)
wait 0.5 seconds
reset list (does display the first image)
wait 0.5 seconds
display the first image again
so before you go to the second image you waited 1 second. Just make it so that when the slider resets it displays the first image and sets the position to the second image so that in the next interval you display the second
I would remake your function like this
//function of slider
function slide(){
slides[position].style.display = "none";
if(position < size - 1){
position++;
}
else{
position = 0;
}
slides[position].style.display = "block";
}
With this you don't have all images displayed at the same time, and the position variable is always the number of the image that is being displayed at the moment, which can be helpfull for further functions
I'm creating an image that changes on click. My code isn't working whats wrong with it?
<div id="img"></div>
<script>
var fNames = ["SD1", "SD2", "SD3", "SD4"]; //File names
var _img = document.getElementById("img"); //Grabs images, groups them
var imgIdx = 0;
_img.style.position = "relative";
_img.style.left = "auto";
_img.style.right = "auto";
_img.style.width = "1920";
_img.style.height = "1280";
_img.style.backgroundImage = "url('images/"+fNames[imgIdx]+".jpg')"; //Retrieves images from file
_img.addEventListener("click", onImageClick); //Allows image click
function onImageClick() {
imgIdx++;
if(imgIdx == 6) {
imgIdx = 0;
}
_img.style.backgroundImage = "url('images/"+fNames[imgIdx]+".jpg')";
}
</script>
You need a unit when you specify the size:
_img.style.width = "1920px";
_img.style.height = "1280px";
When making the index wrap around you are using 6, but it should be 5. Better yet, use the length of the array, that way you don't need to change that part of the code if the array changes:
if(imgIdx > fNames.length) {
imgIdx = 0;
}
I'm trying to use JavaScript to list images 01-40 in order automatically.
Like this:
<img src="01.jpg" />
<img src="02.jpg" />
<img src="03.jpg" />
<img src="04.jpg" />
<img src="05.jpg" />
...
I don't want to write each img src manually, as I want to use this on multiple pages
I'd like the image starting and ending number to be variables that I can edit easily.
You need the parent element for imgs:
for ( var i = FIRST_NUMBER ; i < LAST_NUMBER ; i++ ) {
var elem = document.createElement("img");
if ( i < 10 ) {
elem.setAttribute("src", "0"+i+".jpg");
} else {
elem.setAttribute("src", i+".jpg");
}
document.getElementById(PARENT_ID).appendChild(elem);
}
function img_create(startIndex, endIndex) {
for (i = startIndex; i <= endIndex; i++) {
var oImg=document.createElement("img");
oImg.setAttribute('src', i+".jpg");
//other attributes you need
document.body.appendChild(oImg);
}
}
Working example: http://jsfiddle.net/Lw3bjcx4/1/
function createImages(count, elementId) {
// Get the container element where you want to create the images
var element = document.getElementById(elementId)
// Loop count times over to create count image elements
for (var i = 0 ; i < count ; i++) {
// Create a new image element
var imageElement = document.createElement('img')
// Set the source to index.jpg where index is 0,1,2,3.... count
imageElement.setAttribute('src', i + ".jpg")
// Append the new image element to the choosen container.
element.appendChild(imageElement)
}
}
// Test to create 10 images.
createImages(10,"imgs")
You can use like this:
var imgdiv = document.getElementById('imgdiv');
var img = imgdiv.getElementsByTagName('img');
for(var i=0;i<40;i++){
img[i].src=i+'.jpg';
}
Here is an alternative to all other answers, where you don't need to use an id to put images in. Just paste the script tag where you need to have the images. For example, if you put it in a div, the script will automatically insert the images in place.
<script type="text/javascript">
var thisScriptNode = document.currentScript;
for(var i = 1 ; i <= 40 ; i++) {
var img = document.createElement("img");
img.src = ("00" + i).substr(-2) + ".jpg";
thisScriptNode.parentNode.insertBefore(img, thisScriptNode);
}
</script>
You can easily change the number of leading zeros. For example, to get numbers with three characters, replace "00" with "000" and -2 with -3.
var to = 10;
var from = 0;
for (i = from; i < to; i++){
var elem = new Element('img', { src: i + '.jpg' });
document.body.appendChild(elem);
}
it will append to <body> images with names from 0.jpg to 9.jpg
You have a div, with 3 images in it.
How to create a simple slideshow that cycles through the images, and displays each image for 5 seconds and goes back to the first image when done and continues looping.
Without using jquery or any other framework.
(function () {
var imgs = document.getElementById('your_div').getElementsByTagName('img'),
index = 0;
imgs[0].style.display = 'block';
setInterval(function () {
imgs[index].style.display = 'none';
index = (index + 1) % imgs.length;
imgs[index].style.display = 'block';
}, 5000);
}());
Example HTML: http://jsfiddle.net/Zq7KB/1/
Edit: Saw a more elegant example above that used .length.
You can use setInterval to set up the timed callback, and set the src of an img element:
window.onload = function() {
var slides = [ "path_to_image_one",
"path_to_image_two",
"path_to_image_three" // ...
],
index = 0,
timer = 0;
// Show the first slide
showNextSlide();
// Show "next" slide every five seconds
timer = setInterval(showNextSlide, 5000);
// The function we call to show the "next" slide
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('theImage').src = slides[index++];
}
};
...where your markup for the image is:
<img id="theImage" src="path_to_initial_placeholder">
Note that I've stored the timer handle in timer but not used it. This is just because you might use it to cancel the timer if you need to stop the slideshow.
Update: Just saw that you want to get the images from a div somewhere (whereas above I've supplied the paths in the code itself). Simple enough to create slides dynamically; revised edition of the above that grabs the images that are direct children of the div with the ID "theDiv":
window.onload = function() {
var slides = [],
index = 0,
timer = 0,
node;
// Get the slides
for (node = document.getElementById('theDiv').childNodes;
node;
node = node.nextSibling) {
if (node.nodeType == 1 && node.tagName == "IMG") {
slides.push(node.src);
}
}
// Show the first slide
showNextSlide();
// Show "next" slide every five seconds
timer = setInterval(showNextSlide, 5000);
// The function we call to show the "next" slide
function showNextSlide() {
if (index >= slides.length) {
index = 0;
}
document.getElementById('theImage').src = slides[index++];
}
};
Well you'd have to get a handle for the <div> first, so if it has an "id" value:
var theDiv = document.getElementById("imgContainer");
Now you just have to set up a timer to cycle through the images:
(function(div, sleep) {
var idx = 0;
var imgs = div.getElementsByTagName('img');
function showOne() {
for (var i = 0; i < imgs.length; ++i)
imgs[i].style.display = 'none';
imgs[idx].style.display = '';
idx = (idx + 1) % imgs.length;
setTimeout(showOne, sleep);
}
showOne();
})(theDiv, 5000);
var image = new Array('/img/1.jpg', '/img/2.jpg', '/img/3.jpg');
setTimeout("show_next()",5000);
function show_next()
{
var container = document.getElementById('image_container');
container.innerHTML = "<img src='" + image[i] + "' />";
if(i==2) { i = 1; }else { i = i + 1; }
}
I thought this was a nice simple answer, but there were a couple of errors.
setInterval rather than setTimeout and the initial index was not set. I also amended to load first image immediately.
var image = new Array('imgs/18/P1050294-XL.jpg', 'imgs/18/P1050293-XL.jpg', 'imgs/18/P1040984-XL.jpg', 'imgs/18/P1040983-XL.jpg', 'imgs/18/P1040982-XL.jpg');
var path = 'mypath';
document.getElementById('slideShow').innerHTML = "<img width='600px' src='" + path + image[0] + "' />" // Load First image
var i = 1; // Set counter to second image, for first use of loop
setInterval("show_next(path)",5000);
function show_next(path)
{
var container = document.getElementById('slideShow');
container.innerHTML = "<img width='600px' src='" + path + image[i] + "' />";
if(i==4) { i = 0; } else { i = i + 1; }
}