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
}
}
Related
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.
is it possible to display 3 images one after another at each button click using a array in JavaScript?
I have an array called
var images = ["image1.jpg","image2.jpg","image3.jpg"]
The way I need the website to load is for the first picture to already be there. Then when I click on the button I want the next picture to be displayed however replacing the image that was there before. I want this to repeat throughout the entire, so when I click on the button, and if the image being displayed was image3, then image1 should be displayed.
I want to share the code I have so far however I don't know where to start. the only code i have is the layout and a variable.
var images = ["image1.jpg","image2.jpg","image3.jpg"]
Try like this.Use 'document.querySelector' do select your button.On clicking button appen images using forEach in body.
var button = document.querySelector('#show');//selects your button
button.addEventListener('click',function(){ // handle click event
var images = ["image1.jpg","image2.jpg","image3.jpg"];//array of valid images
images.forEach(function(image){
img = document.createElement('img');//creates a img element
img.src = image;//sets src of img tag
document.body.appendChild(img)//appends into body
});
});
<button id="show">
Show images
</button>
Pure JS solution.
var images = ["http://placehold.it/350x150", "http://placehold.it/250x150", "http://placehold.it/150x150"];
var elem = document.getElementById('img');
var i = 0;
window.onload = function() {
elem.setAttribute("src", images[i]);
}
elem.addEventListener('click', function() {
(i < images.length-1) ? i++ : i = 0;
this.setAttribute("src", images[i]);
});
<img src='' id='img'>
jQuery solution.
var images = ["http://placehold.it/350x150", "http://placehold.it/250x150", "http://placehold.it/150x150"];
var i = 0;
$(document).ready(function() {
$('#img').attr('src', images[i]);
});
$('#img').click(function() {
(i < images.length-1) ? i++ : i = 0;
$('#img').attr('src', images[i]);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<img src='' id='img'>
I think I'm missing an obvious rule here and it would be great to get it clarified -
I'm trying to write an image preloader and I'm following the advice given on this posting:
Preloading images in Javascript? Without jQuery
I can see how it all works up until:
for(var i = 0; i < imageList.length; i++ ) {
var imageObject = new Image();
imageObject.src = imageList[i]; }
I keep thinking this would simply change/overwrite the src property at every iteration, leaving imageObject.src as the last image in the list at the end of the loop, though clearly the function is meant for using multiple images.
So I'm assuming it leaves imageObject containing an array of images but I'm not sure how it does this. What do I have wrong?
What you have will "probably" work. But, it's not the ideal way to do things because it relies on some undocumented aspects of a browser and garbage collection. See here and here for safer ways to do this. I'll try to explain what your code is doing.
When you do this line:
var imageObject = new Image();
it is creating a new DOM image object and placing a reference to that object in the variable imageObject.
When you do this line:
imageObject.src = imageList[i];
it is assigning the .src property of that new image object. This will NOT be overwriting the .src property on the previous image object.
But, because the previous image objects are not stored anywhere and no other javascript has any references to them, they are available for garbage collection by the browser and it is free to get rid of them at any time. To use this for reliable caching, you are hoping that the browser does not cancel the networking operation in progress that is loading the images and you are hoping that they still get into the browser cache so they are preloaded.
It is much safer to store the imageObject in an array as the other solutions I've pointed you to will do. This keeps them from being garbage collected so there is no risk that their image loading will be cancelled.
For example, it would be safer to do this:
var imgs = [];
for (var i = 0; i < imageList.length; i++ ) {
var imageObject = new Image();
imageObject.src = imageList[i];
imgs.push(imageObject);
}
The previous two references to other solutions to this do something similar, but package this in a function and one also has the ability to notify you when all the images have finished preloading.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript">
var imageList = new Array("dummyImg1.jpg", "dummyImg2.jpg");
var imagePlaceholder = new Array(imageList.length);
function waitImagesLoaded() {
var allImagesLoaded = true;
for (var i = 0; i < imageList.length && allImagesLoaded; i++) {
allImagesLoaded &= imagePlaceholder[i].complete;
}
if (allImagesLoaded) {
for (var i = 0; i < imageList.length; i++) {
var imgElemIdToReplace = "img" + String(i + 1);
replaceElem(imagePlaceholder[i], document.getElementById(imgElemIdToReplace));
}
} else {
window.setTimeout(waitImagesLoaded, 500);
}
}
function replaceElem(substituteElem, elemToReplace) {
var parentNode = elemToReplace.parentNode;
parentNode.replaceChild(substituteElem, elemToReplace);
}
</script>
</head>
<body>
<img id="img1" src="" alt="">
<img id="img2" src="" alt="">
<script type = "text/javascript">
for (var i = 0; i < imageList.length; i++) {
var imageObject = new Image();
imageObject.src = imageList[i];
imagePlaceholder[i] = imageObject;
}
window.setTimeout(waitImagesLoaded, 500);
</script>
</body>
</html>
I'm injecting JavaScript code into a website for personal use, using a Google Chrome extension... I'd like to hide all images before the page loads... I've got the script to run before anything loads, but can't seem to get the correct code to hide the array of images... something like:
function beforeload(){
document.getElementsByTagName('img')[0].style.display = "none"
}
Basically i want all the image tags to have style="display:none" added to the attributes. how do i do this?
You need to loop on them
var images = document.getElementsByTagName('img');
for (i = 0; i < images.length;i++ ) {
images[i].style.display = "none";
}
Amr has got the way to do it with javascript. If you add jquery to the page, it only takes one line
$('img').hide();
Below code will only hide images of all image elements
let images = document.getElementsByTagName("img");
let images_length = images.length;
for (let i = 0; i < images_length; i++) {
images[i].style.setProperty("display", "none", "important");
}
but what if images are displayed using CSS ?
Solution for all elements
let images = document.getElementsByTagName("img");
let images_length = images.length;
for (let i = 0; i < images_length; i++) {
images[i].style.setProperty("display", "none", "important");
}
/** now also hide images which are implemented in css */
let all_elements = document.querySelectorAll("*");
for(let i = 0 ; i < all_elements.length ; i++){
all_elements[i].style.setProperty("background-image","unset","important");
}
.image {
width : 100px;
height : 100px;
background-image : url(https://image.shutterstock.com/image-photo/aerial-view-main-faisal-mosque-600w-1242735640.jpg);
}
<img src="https://image.shutterstock.com/image-photo/aerial-view-main-faisal-mosque-600w-1242735640.jpg" width="100" height="100">
<div class="image"></div>
<div> To show images plz comment/remove js </div>
Check this out:
http://ncthakur.itgo.com/js09.htm
It's not exactly what are you looking for, but you can use some part of it.
It took me 7 seconds to find it on google ;)
UPDATE: I've edited the code below to show what I was using when I tried to work with CSS visibility. I'm still stuck with this problem. I've also tried to remove the preloader() function from the body onLoad, but I can't use getElementById because the element hasn't loaded. My final thought was to just call rand(5) from within the HTML itself so that it adds a number to the end of the image filename if Javascript is enabled, but I'm not even sure how to incorporate that directly into the HTML. Any help would be greatly appreciated!
I created a slideshow with Javascript. The HTML calls a static image to display in the event Javascript is not enabled in the browser. If Javascript is enabled in the browser, it is supposed to load a random image in the place of the static image.
The problem I'm encountering is when Javascript is enabled, you see the static image load with the page and then, if the random image is different, you see it quickly load right after that. So it looks like two images cycling quickly on page load.
Here is the Javascript code I'm using:
// Define images used in slideshow
imgArray = new Array(
"header_img1.jpg",
"header_img2.jpg",
"header_img3.jpg",
"header_img4.jpg",
"header_img5.jpg"
);
baseURL = "images/";
// Preload slideshow images
function preloader() {
domElement = document.getElementById('gallery-image');
domElement.style.visibility = "hidden";
// counter
var i = 0;
// create object
imageObj = new Image();
// start preloading imgArray
for (i=0; i<3; i++) {
imageObj.src=imgArray[i];
}
}
// Select random image to display for slideshow
function random_img() {
domElement.style.visibility = "visible";
rand = Math.round(Math.random()*(imgArray.length - 1));
document["faces"].src = baseURL + imgArray[rand];
rand += 1;
}
Here is the accompanying HTML:
<body onLoad="preloader();random_img();">
.
.
.
<a href="#" onclick="f_slideshow(-1);return false;">
<img src="images/header_img1.png" alt="" width="26" height="207" /></a>
<img src="images/header_img1.jpg" alt="" width="529" height="197" class="img-1" name="faces" />
<a href="#" onclick="f_slideshow(1);return false;">
<img src="images/header_img2.png" alt="" width="27" height="207" /></a>
How do I change what I have so when Javascript is enabled, you don't see the two cycling images?
In your preLoader() manipulate the style to hide the elements you wish to hide if javascript is enabled.
This way, if it is enabled the elements will hide, if it is not, the clearly the javascript to hide them will not run.
example
var domElement = document.getElementById('id-of-element');
domElement.style.display = 'none';
This is the JavaScript code that solved my problem:
// Define images used in slideshow
imgArray = new Array(
"header_img1.jpg",
"header_img2.jpg",
"header_img3.jpg",
"header_img4.jpg",
"header_img5.jpg"
);
baseURL = "images/";
// Hide static image and preload slideshow images
function preloader() {
// counter
var i = 0;
// create object
imageObj = new Image();
// start preloading imgArray
for (i=0; i<3; i++) {
imageObj.src=imgArray[i];
}
}
// Control previous/next functions of slideshow
numImages = imgArray.length;
function f_slideshow( xflip ) {
// grab source of current image
var curImage = document["faces"].src;
// get image number from string and convert to int
curImage = parseInt(curImage.substring(curImage.length-5, curImage.length));
// create source for next/previous link
curImage = curImage + xflip;
if (curImage > numImages)
{ curImage = 1 ; }
if (curImage == 0)
{ curImage = numImages ; }
document["faces"].src = baseURL + imgArray[curImage - 1];
}