Displaying different images on page refresn and using timers with javascript - javascript

I made a basic one page html website and styled it. I have a small image gallery (6 images) and I want to use JS to display these images in a different order every time the page is refreshed. If the page isn't refreshed, I want it to be on a timer to refresh the images.
I know I would have to use Math.random, and I could use onload with an interval timer to change the images. I've done some research and I can't figure out how to implement this. Could anyone point me in the right direction?
Here's the html portion of the image gallery:
<section id="gallery">
<img src="./images/1.jpg" alt="img0">
<img src="./images/2.jpg" alt="img1">
<img src="./images/3.jpg" alt="img2">
<img src="./images/4.jpg" alt="img3">
<img src="./images/5.jpg" alt="img4">
<img src="./images/6.jpg" alt="img5">
</section>

Here's an example.
const getRandomNumber = (function() {
var nums = [1,2,3,4,5,6];
var current = [];
function rand(n) {
return (Math.random() * n)|0;
}
return function() {
if (!current.length) current = nums.slice();
return current.splice(rand(current.length), 1);
}
}());
const images = document.querySelectorAll('#gallery img');
getRandomImages = () => {
const imagesNums = [];
for (let i = 1; i < 7; i++) {
imagesNums.push(getRandomNumber());
}
images.forEach((img, index) => {
img.src = `./images/${imagesNums[index]}.jpg`
})
}
setInterval(() => {
getRandomImages()
}, 10000);
<section id="gallery">
<img src="./images/1.jpg" alt="img0">
<img src="./images/2.jpg" alt="img1">
<img src="./images/3.jpg" alt="img2">
<img src="./images/4.jpg" alt="img3">
<img src="./images/5.jpg" alt="img4">
<img src="./images/6.jpg" alt="img5">
</section>

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>test</title>
<link rel="stylesheet" type="text/css" href="styles.css">
</head>
<body>
<img id="image" src="./images/1.jpg">
<script type = "text/javascript">
var image = document.getElementById("image");
var currentPos = 0;
var images = ["./images/2.jpg", "./images/3.jpg",
"./images/4.jpg","./images/5.jpg,./images/6.jpg]
function auto_pic() {
if (++currentPos >= images.length)
currentPos = 0;
image.src = images[currentPos];
}
setInterval(auto_pic, 4000);
</script>
</body>
</html>`

Just replace Onclick event with Window Refresh Event
HTML
<div id="box">
<img id="image" />
</div>
<br />
<input type="button" value="Randomize!" onClick="randImg()" />
Javascript
var images = [
"https://png.pngtree.com/thumb_back/fh260/background/20190222/ourmid/pngtree-blue-atmospheric-background-image_50584.jpg",
"https://radioralitafm.com/wp-content/uploads/2018/01/Blue-Background-Images-HD-Wallpapers-Backgrounds-of-Your-....jpg",
"https://sinargarudaprima.files.wordpress.com/2013/08/blue-abstract-vista-wallpaper00000.jpg",
"https://i.pinimg.com/originals/09/43/75/094375b4af674b559ac8a00a8c8d6662.jpg"];
function randImg() {
var size = images.length
var x = Math.floor(size * Math.random())
document.getElementById('image').src = images[x];
}
randImg();
Here Demo JSFIDDLE

Keep all the image sources in an array.
const imgSources = ['./images/1.jpg', './images/2.jpg', './images/3.jpg'];
Select a random item from your list
const randomItem = Math.floor(Math.random())
Then select the image from the html and set the source attribute
const image = document.querySelector('#gallery'); // Assuming you have only 1, replace with id
image.setAttribute('src', randomItem);
We have done the part for a random image. Now its similar with a setInterval
setInterval(() => {
const randItem = Math.floor(Math.random() * arr.length);
image.setAttribute('src', randItem);
}, 3000); // 3s
Thats it!
I'd recommend making a function for a random no and then setting the attribute in both places so you don't repeat yourself
You can make a function like this -
function changeImage(img) {
const randItem = Math.floor(Math.random() * arr.length);
img.setAttribute('src', randItem);
}
This function can be called inside the setInterval and in the start of the code. Remember to pass in the image!
Cheers

Here is how I would do it (given your HTML above):
Start with your "gallery" section empty. Just put the section there with no images.
Create a function that writes the content (image tags) of your "gallery" section.
Call that function on page load.
Set a timer to either run your function on a schedule, or to refresh the page after a certain amount of time.
I was hesitant to give the complete code for what looks like it could be a homework assignment, but I see several other full answers. So here is what this looks like:
<body onload="drawImages()">
<section id="gallery">
</section>
<script>
function drawImages() {
let myImage = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg"];
shuffle(myImage);
// You'll have to play with this to get the alt text as you
// specified, if that is important.
let imageHTML = "";
for (let i = 0; i < myImage.length; i++) {
imageHTML += '<img src="./images/' + myImage[i] + '" alt="' + myImage[i] + '">';
}
document.getElementById('gallery').innerHTML = imageHTML;
}
function shuffle(array) {
// Try your shuffle function first. If you can't get it working,
// copy the complete working function from the accepted answer
// at:
// https://stackoverflow.com/questions/2450954/how-to-randomize-shuffle-a-javascript-array
}
setInterval(function(){drawImages();}, 2000);
</script>
</body>
Good luck.

Related

Image Loading detecting using Javascript

I have a lot of images (of 5 categories) in my website which make it load slowly.
I set every image with Attribute "data-src" containing its real source, and I update its source attribute with this "data-src" attribute for every image in this categroy (inside a for loop), whenever the relevant category is chosen (clicked).
HTML:
<img loading="lzay" class="post_image" data-src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg">
JAVASCRIPT:
for(i = 0; i< selection.length; i++){
let data_src = selection[i].children[2].getAttribute("data-src");;
selection[i].children[2].src = data_src;
}
How can I tell when all of the images of a category was loaded to the site?
(some code continue to run after the for loop is done, yet not all the images loaded and I wish the rest of the code will fire only after they are loaded to page).
Try this. I didn't have much time to come up with it, but it might work. Sorry if it doesn't.
index.html
<img id="img1" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg"/>
<img id="img2" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg"/>
<img id="img3" src="https://i.ibb.co/FswR5KB/Pics-Art-06-22-07-48-49.jpg"/>
<script type="text/javascript" src="script.js"></script>
script.js
const img1 = document.getElementById("img1");
const img2 = document.getElementById("img2");
const img3 = document.getElementById("img3");
const imgArray = [
img1,
img2,
img3
]
let imgsLoaded = 0;
for (let i = 0; i < imgArray.length; i++) {
imgArray[i].onload = function () {
imgsLoaded++;
}
if (imgsLoaded >= imgArray.length) {
// all images are loaded
}
}

How to display one image in loop?

I'm trying to display one image in loop. Knowing the path and image-name are okay is this example, how to display one image in loop, and when the image haven't been found, the browser displays the last right image-name until the image-name is found?
#{int j=1;}
<img src="" />
<script>
(function () {
for (var i = 1; true; i++) {
#{ string file = "/MonitoringN/../bitmaps/" + j + ".png"; bool a = System.IO.File.Exists(file) == true; }
var str = "/MonitoringN/../bitmaps/" + i + ".png";
var b = "#a";
if (b)
{
setInterval(function () { $('img').prop('src', str); }, 1000);
} else {
i--;
#{j--;}
}
#{j++;}
}
});
</script>
Because when I execute this code, I get a blank image, and then I can't see the page is loading.
Thanks a lot!
I think I know what you are trying to do ...
If I understand the question correctly, you have a list of images and you want to try to open them until one of them is found. If an image is NOT found, you want to skip to the next one.
First -- I'd simply for your question by separating the Razor stuff and the Javascript off into very separate pieces. In fact, I'm going to skip Razor entirely.
<html>
<head>
<title>A test</title>
</head>
<body>
<img src="http://x.invalid" id="myImage">
<script>
var imgs = [
"http://x1.invalid/none",
"https://www.google.com/images/srpr/logo11w.png",
"http://thedailywtf.com/Resources/Images/Primary/logo.gif"
];
var imageIndex = 0;
function tryNextImage() {
var img = document.getElementById("myImage");
img.onerror = function() {
imageIndex++;
tryNextImage();
}
img.src = imgs[imageIndex];
}
// start the ball rolling
tryNextImage();
</script>
</body>
</html>

trying to make a slide show with videos and images using an array but the pictures wont show up

im making a slideshow using videos and images with an array in
javascript i have a next button and previous button. The videos work
with the buttons and play and everything just when i added the
pictures into the array and keep clicking next they wont show up not
sure how to do this. Also every time you hit next or previous the
caption updates to match whats displaying, that also works fine. also
my videos only work in chrome any idea on how to fix that too? here is
my html and javascript code
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>javascript homework 2</title>
<link href="css/styles.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="mainImg">
<h2 id="caption">movie1</h2>
<video id="myVideo" src="video/movie1.mp4" type="video/mp4"/></video>
</div>
<div id="controls">
<div id="playToggle" class="player-button">Play</div>
</div>
<div id="links">
<ul>
<a onClick="nextPhoto();" href="#">Next</a>
<a onClick="prePhoto();" href="#">Previous</a>
</ul>
</div>
</body>
<script src="js/javascript.js"></script>
</html>
// JavaScript Document
/*---Global varibales--*/
var currentImage = 0;
var count = 0;
var videos = new Array("movie1", "movie2", "movie3","Dk1", "Dk2", "Dk3");
var captions = new Array("movie1", "movie2", "movie3", "Dark Knight 1", "Dark Knight 2", "Dark Knight 3");
var video = document.createElement("video");
var playPauseButton = document.getElementById('playToggle');
function switchVideo() {
video.setAttribute('src',videoPaths[CurrentVideos]);
video.onload = function() {
currentVideo++;
if (currentVideo >= videoPaths.length) {
currentImage = 0;
}
}
}
function changeVideo(movie)
{
var thisVideo = "video/"+videos[movie]+".mp4";
document.getElementById("myVideo").src = thisVideo;
document.getElementById("caption").innerHTML = captions[movie];
count = movie;
}
function nextPhoto()
{
count++;
if(count==videos.length)
{
count = 0;
}
var thisVideo = "video/"+videos[count]+".mp4";
document.getElementById("myVideo").src = thisVideo;
document.getElementById("caption").innerHTML = captions[count];
}
function prePhoto()
{
count--;
if(count < 0)
{
count = videos.length-1;
}
var thisVideo = "video/"+videos[count]+".mp4";
document.getElementById("myVideo").src = thisVideo;
document.getElementById("caption").innerHTML = captions[count];
}
playPauseButton.onclick = function() {
if (myVideo.paused) {
myVideo.play();
this.innerHTML = "Pause";
} else {
myVideo.pause();
this.innerHTML = "Play";
}
};
In the nextPhoto() function you set the current image or video by using
var thisVideo = "video/"+videos[count]+".mp4";
This works for mp4 files but for nothing else. I recommend you add the file extensions to your array like so.
var videos = ["movie1.mp4", "image1.png"]; // and so on....

Add Next and Prev Buttons To Rotating Banner

I'm not knowledgeable in JS and Jquery so I'm really hoping someone here could help me out.
I want my banner to change image on page load or refresh and I found this code:
<script type="text/javascript">
window.onload = function () {
var random = document.getElementById('random');
var pictures = new Array('images/icn_slide-1.jpg','images/icn_slide-2.jpg','images/icn_slide-1.jpg','images/icn_slide-2.jpg');
var numPics = pictures.length;
if (document.images) {
var chosenPic = Math.floor((Math.random() * numPics));
random.style.background = 'url(' + pictures[chosenPic] + ')';
}
}
The script above works pretty well(background image changes every refresh) but now I want to add a previous and next button(actually I already did) so that when viewers click on next/previous it would display another image. Is there a simple way to do this? How do I make my next and previous button work? Any help would be greatly appreciated. Thanks!
This is the only content inside the of my html:
<div id="random" style="width: 1399px; height:515px; margin:auto;">
<div id="slide_control" class="clearfix">
<span id="prev"><img alt="" title="" src="images/icn_nav-arrow2.png" /></span>
<span id="next"><img alt="" title="" src="images/icn_nav-arrow.png" /></span>
</div>
</div>
It's the #random div that changes background image on refresh as of now and I want it just like that. I added the "slide_control" which contained the "prev" and "next" button and what I want them to do is to also change the background-image of #random when they're clicked.
Most JS/JQquery slider and plugins comes with buttons and controllers but they auto-play images and if I disable the autoplay, they don't change banner/background on refresh.
I only want the images/background to randomly change on refresh or change when prev/next buttons are clicked but I don't know how to achieve this.
Here's a basic example of what you are asking for:
<script type="text/javascript">
function rotateImage(idx) {
var random = document.getElementById('random');
if (document.images) {
random.style.background = 'url(' + pictures[idx] + ')';
selectedImage = idx;
}
}
function getNext() {
var nextImage = selectedImage + 1;
if (selectedImage >= numPics) {
nextImage = 0;
}
rotateImage(nextImage);
}
function getPrev() {
var prevImage = selectedImage - 1;
if (selectedImage < 0) {
selectedImage = numPics -1;
}
rotateImage(prevImage);
}
var pictures = new Array('images/icn_slide-1.jpg','images/icn_slide-2.jpg','images/icn_slide-1.jpg','images/icn_slide-2.jpg');
var numPics = pictures.length;
var selectedImage = null;
window.onload = function () {
var chosenPic = Math.floor((Math.random() * numPics));
rotateImage(chosenPic);
document.getElementById('next').onclick = getNext;
document.getElementById('prev').onclick = getPrev;
}
</script>

Javascript image load and display

I have a web page that shows an image and two arrows, with Javascript.
When the right arrow is clicked, the index increments and a new image should be loaded.
When the left arrow is clicked, the index decrements and a new image should be loaded.
I added some alerts to the code which shows that the index is incremented, but the new image is still not displayed. I would appreciate pointers on what's wrong with the code.
Only the initial image is always shown and it's not updated. The link change colors and the alerts are displayed.
<html>
<head>
<title> Gallery</title>
</head>
<script type="text/javascript">
var rightTarget;
var leftTarget;
var index = 516;
function rightLinkClicked(e) {
rightTarget = e.target;
rightTarget.style.color = "green";
leftTarget.style.color = "black";
index = index +1;
alert ("right1")
var img;
img=document.getElementsByTagName('img');
img.src="pics/IMG_0" + index + ".JPG";
alert ("right2 - index = IMG_0" + index + ".JPG")
}
function leftLinkClicked(e) {
leftTarget = e.target;
leftTarget.style.color = "red";
rightTarget.style.color = "black";
if (index >516) {
index = index -1;
}
var img;
img=document.getElementsByTagName('img');
img.src="pics/IMG_0" + index + ".JPG"
alert ("left - index = "+ index)
}
function addListeners() {
var rightLink = document.getElementById("rightlinkid");
rightLink.addEventListener('click', rightLinkClicked, false);
var leftLink = document.getElementById("leftlinkid");
leftLink.addEventListener('click', leftLinkClicked, false);
}
window.addEventListener('load', addListeners, false);
</script>
</head>
<body>
<a id="leftlinkid">Left Link
<img src="icons/left.gif"; alt="left arrow" title="">
</a>
<div id="myimg">
<img id="img" src="pics/IMG_0516.JPG"; alt="start arrow" title="" width="640" height="480">
</div>
<a id="rightlinkid">Right Link
<img src="icons/right.gif"; alt="right arrow" title="">
</a>
</body>
</html>
You are using getElementsByTagName which returns a collection of DOM elements, which is not the same as your single image. You should do
img = getElementById('img');
The code img=document.getElementsByTagName('img'); returns a collection. You need to specify which images' source you want to modify, like img[index + 1].src = .... I think you will want to use index + 1 so that it doesn't start counting with the first image (the left arrow). A better solution might be to give all of your images the same class name and find by class (document.getElementsByClassName('myClass');).

Categories

Resources