load gif until page is fully load - javascript

I want to display a gif image until the website is completely loaded.
Once I click button (onclick=window.open) a new page opened but is blank and the gif is only appearing once the website is loaded.
I want once clicking the button a new page opened and showing immediately the gif and disappear once the page is loaded
Can anyone help me, what I’m doing wrong or what is missing to load the gif when the page is loading? Here is my code, thank you so much
land.php file:
<button type="button"
onClick="window.open('./gremo.cfm ',
toolbar=no,
menubar=no,
scrolling=yes,
scrollbars=yes
')">
</button>
gremo.php file:
<head>
<script type="text/javascript">
function showHide(elementid){
if (document.getElementById(elementid).style.display == 'none'){
document.getElementById(elementid).style.display = '';
} else {
document.getElementById(elementid).style.display = 'none';
}
}
window.onload = function () { reSizeTextarea(); showHide('loadingd'); }
</script>
</head>
<body>
<div id="loadingd" align="center">
<br/><br/><br/><img src="./loading.gif">
</div>
</body>

Note that when you are running locally, resources are loading fast.. very fast
Don't forget to use your developer tools and configure network throttling (to simulate a slower connection). That should simulate a "real" scenario and let you test your code better
Here is a screenshot from chrome... enjoy!

When you have a lot of content, it will take time to load. The image will show and than hide when the onload event happens. Now run it again, the content is cached and loading will take no time at all.
So load time depends on what there is to load/render, how it is loaded, and if it is cached or not.
window.onload = function () {
document.getElementById("loading").remove()
document.querySelector(".content").removeAttribute("hidden")
}
[hidden] {
display: none
}
#loading {
width: 300px;
}
<img id="loading" src="https://media.giphy.com/media/3o7bu8sRnYpTOG1p8k/source.gif" />
<div class="content" hidden>
<img src="http://placekitten.com/200/200" />
<img src="http://placekitten.com/100/100" />
<img src="http://placekitten.com/300/300" />
<img src="http://placekitten.com/400/400" />
<img src="http://placekitten.com/500/500" />
</div>
In your example, you have nothing that takes time to load other than the loading image. So as soon as your image is loaded, the window.onload is triggered. That is why it flashes.
If you want the image to show, you can add some logic saying if I have not been here for X seconds, than wait....
var startTime = new Date()
window.onload = function () {
var loadTime = new Date()
var diff = loadTime - startTime;
if (diff > 5000) {
toggleLoad()
} else {
window.setTimeout(toggleLoad, 5000 - diff)
}
}
function toggleLoad () {
document.getElementById("loading").remove()
document.querySelector(".content").removeAttribute("hidden")
}
[hidden] {
display: none
}
#loading {
width: 300px;
}
<img id="loading" src="https://media.giphy.com/media/3o7bu8sRnYpTOG1p8k/source.gif" />
<div class="content" hidden>
<img src="http://placekitten.com/200/200" />
<img src="http://placekitten.com/100/100" />
<img src="http://placekitten.com/300/300" />
<img src="http://placekitten.com/400/400" />
<img src="http://placekitten.com/500/500" />
</div>
To ensure the loading gif loads fast, on the parent page, you probably want to preload it
var img = new Image()
img.src = "your.gif"

Related

Unable to lazy load images with JavaScript

I am unable to get my images to lazy load with JavaScript. For some reason, the images just do not show up at all when I change the html from src to data-src. Then when I use an intersectionObserver to lazy load images, I can't get any images to show up on the page. Attached is my html, css and JS code;
html:
<div class="photo__container photo__container--one">
<img
data-src="portrait/1-vertical.jpeg"
alt=""
class="fade-in-img img-vertical-lazy"
/>
<img
data-src="portrait/2-vertical.jpeg"
alt=""
class="fade-in-img img-vertical-lazy"
/>
<img
data-src="portrait/3-vertical.jpeg"
alt=""
class="fade-in-img img-vertical-lazy"
/>
</div>
CSS:
.img-vertical-lazy {
height: 70rem;
width: auto;
}
JS:
const lazyImages = document.querySelectorAll('.img-vertical-lazy');
const appearLazy = {
threshold: 0.1
};
const lazyLoading = new IntersectionObserver((entries) => {
entries.forEach(entry => {
if (!entry.isIntersecting) return;
entry.target.src = entry.target.getAttribute('data-src');
lazyLoading.unobserve(entry.target);
});
}, appearLazy);
lazyImages.forEach(image => lazyLoading.observe(image));
There are several ways to do that but it depends on your purpose of using lazy loading. In most cases, it is for SEO (i.e. for fast page loading).
If you are lazy loading images only for a fast page speed score then you can add this code to your page.
Here is a working example:
An image will be loaded when you scroll inside div.
<html>
<body>
<div id="mydiv" style="width:500px;height:300px;overflow:scroll;">
<h1>Images are not technically inserted into a web page; images are linked to web pages. The tag creates a holding space for the referenced</h1>
<div class="photo">
<img data-src="https://images.freeimages.com/images/small-previews/648/bs-04-1255720.jpg"/>
</div>
<h2>Images are not technically inserted into a web page; images are linked to web pages. The tag creates a holding space for the referenced image.Images are not technically inserted into a web page; images are linked to web pages. The tag creates a holding space for the referenced image.</h2>
</div>
<script>
var sw = 0;
document.getElementById('mydiv').onscroll=function(){
if(sw==0){
sw=1;
const lazyImages = document.querySelectorAll('img');
for (let i = 0; i < lazyImages.length; i++) {
lazyImages[i].src = lazyImages[i].getAttribute('data-src');
}
}
}
</script>
</body>
</html>
Tip: use window.onscroll to apply effect on whole webpage

how to change the src of an image when clicking and it return to the original after some time?

I have a page that displays several hidden divs when clicking on image-buttons (next and previous). sometimes takes a few seconds for its content to show up correctly, so I had the idea of ​​delaying the functions a bit to "give time" for the content to "prepare". While that time the image exchanges for a gif.
I already started and saw that it works, I got a simple way with tris.src to change the img and setInterval for the delay, direct on my onclick="", but I need the original image to automatically return to the original after 2 or 3 seconds because it can showed again (when clicked on previous button) and should not to be a gif anymore! and don't know how to do this. can you help me?
CSS:
div1, #div2 {width: 100px; height: 100px; background: yellow;position: relative;
next {position: absolute bottom: 20px; left: 20px}
}
HTML & JS:
<div id="div1">
content1
<img src="next.png" id="next" onclick="setTimeout(replace, 1000); this.src='prev.png'">
<input type="hidden" value="prev.png" id="hdnPreviousPng" />
</div>
<div id="div2" style="display: none">content2
<img src="next.png" id="next" onclick="setTimeout(replace2, 1000); this.src='prev.png'">
<input type="hidden" value="prev.png" id="hdnPreviousPng" />
</div>
<script>
function replace() {
document.getElementById("div1").style.display="none";
document.getElementById("div2").style.display="block";
setInterval(function(){
let originalSrc = $('#hdnPreviousPng').val();
$('#next').attr('src', originalSrc);
}, 3000);
}
function replace2() {
document.getElementById("div2").style.display="none";
document.getElementById("div1").style.display="block";
setInterval(function(){
let originalSrc = $('#hdnPreviousPng').val();
$('#next').attr('src', originalSrc);
}, 3000);
}
</script>
You could just use a simple data attribute to store some state and swap in and out image source tags.
Here is an example of how this would work using JavaScript:
function clicked() {
replace();
setTimeout(replace, 1000);
}
function replace() {
var next = document.getElementById("next").getAttribute("data-img-src");
var current = document.getElementById("next").src;
document.getElementById("next").setAttribute("data-img-src", current);
document.getElementById("next").src = next;
}
<div id="div1">
<img id="next" src="http://via.placeholder.com/100?text=first" data-img-src="http://via.placeholder.com/100?text=second" onclick="clicked();">
</div>
If you need to account for multiple clicks and still return to the original image you will need some more state and can try this:
function clicked() {
replace();
setTimeout(replaceOriginal, 1000);
}
function replace() {
var next = document.getElementById("next").getAttribute("data-img-src");
document.getElementById("next").src = next;
}
function replaceOriginal(){
var original = document.getElementById("next").getAttribute("data-img-original");
document.getElementById("next").src = original;
}
<div id="div1">
<img id="next" src="http://via.placeholder.com/100?text=first" data-img-original="http://via.placeholder.com/100?text=first" data-img-src="http://via.placeholder.com/100?text=second" onclick="clicked();">
</div>

How can I link image to another page?

I am currently working on my school project website and I am really having a hard time coding.
So in my website I made an image slider and I wanted the images to be linked to another page, like if the user clicked the image they will be redirected to another page that contains information regarding the image they clicked. I also wanted a hover text when the mouse is pointed on the image that shows the title of it.
I tried to search and to watch videos on how to link images but nothing works.
Here's my code:
<script type="text/javascript">
<!-->
var image1=new Image()
image1.src="e.jpg"
var image2=new Image()
image2.src="g.jpg"
var image3=new Image()
image3.src="h.jpg"
//-->
</script>
<style type="text/css">
#gallery {
width: 100%;
height: 100%;
}
#gallery img {
width: 55%;
}
</style>
<DOCTYPE!html>
<html>
<body>
<center>
<div id="gallery">
<img src="e.jpg" name="slide" alt="Track race">
<script type="text/javascript">
<!--
var step=1
function slideit(){
document.images.slide.src=eval("image"+step+".src")
if(step<3)
step++
else
step=1
setTimeout("slideit()",2500)
}
slideit()
//-->
</script>
</div>
</center>
</body>
</html>
onclick on a image to navigate to another page using Javascript
3rd best answer:
I'd set up your HTML like so:
<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />
Then use the following code:
<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
var image = images[i];
image.onclick = function(event) {
window.location.href = this.id + '.html';
};
}
That assigns an onclick event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id attribute plus the .html extension. It's essentially the pure Javascript implementation of #JanPöschko's jQuery answer.

Get image src from a image in a slideshow

I've been looking around much today and spend a few hours trying to get something done. For a client I am creating a slideshow with a lightbox when clicked on an image. The slideshow and lightbox both work, but I don't get the right image in the lightbox yet.
This is the code that loads the slideshow and when clicked on an image opens the lightbox.
(The images for the slideshow get loaded by a php script and turned into a Javascript array)
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/"+galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
}
</script>
<div style="width: 170px; height: 160px">
<a href = "javascript:void(0)" onclick = "document.getElementById('light').style.display='block';document.getElementById('fade').style. display='block'">
<img id="slideshow" src="" />
</a>
<div id="light" class="white_content">
<img id="lightImg" src="" />
<script>
var image = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", image);
</script>
I now try to create a variable named "image"and let this contain the src of the current image in the slideshow. So I can load this to the image in the lightbox.
Hopefully some one can give me some usefull tips. I am pretty new in the Javascript language.
The script for the slideshow came from: http://www.javascriptkit.com/javatutors/externalphp2.shtml
Regards Koen.
These days there really is no excuse for using obtrusive Javascript (Stuff inside your HTML attributes, ideally it should be in an external file. http://en.wikipedia.org/wiki/Unobtrusive_JavaScript).
I have done you the favour of cleaning up your code a bit, and changed it where you seemed to be going wrong. As DotNetter has already pointed out it would be sensible to use jQuery in this instance, as it really does simplify things. However, I'm going to assume that for some reason you want it in plain js. Below is a simplification of the code that you posted with the correct change.
<style type="text/css">
.wrapper {
width: 170px;
height: 160px;
}
</style>
<script type="text/javascript">
var curimg=0;
function rotateimages(){
document.getElementById("slideshow").setAttribute("src", "images/" + galleryarray[curimg]);
curimg=(curimg<galleryarray.length-1)? curimg+1 : 0;
}
window.onload = function(){
setInterval("rotateimages()", 1000);
document.getElementById("slideshow").onclick = function () {
var imageSrc = document.getElementById("slideshow").src;
document.getElementById("lightImg").setAttribute("src", imageSrc);
document.getElementById('light').style.display = 'block';
document.getElementById('fade').style.display = 'block';
}
}
</script>
<div class='wrapper'>
<img id="slideshow" src="" />
<div id="light" class="white_content">
<img id="lightImg" src="" />
</div>
</div>
Before, you were getting the src of the current image when the page loaded, you need to be getting the src of the image when the user clicks on the

Hide Content Loading Gif

I have two large image files in a div on a page that take several seconds to load. How can I hide the loading content while a "loading gif" appears and then have the content appear once it has fully loaded?
I don't really know anything about javascript but I tried using this code. It did half of what I wanted it to do. The "loading gif" worked but the problem was that the content was visible as it was loading.
http://aaron-graham.com/test2.html
<div id="loading" style="position:absolute; width:95%; text-align:center; top:300px;">
<img src="img/parallax/ajax-loader.gif" border=0>
</div>
<script>
var ld=(document.all);
var ns4=document.layers;
var ns6=document.getElementById&&!document.all;
var ie4=document.all;
if (ns4)
ld=document.loading;
else if (ns6)
ld=document.getElementById("loading").style;
else if (ie4)
ld=document.all.loading.style;
function init()
{
if(ns4){ld.visibility="hidden";}
else if (ns6||ie4) ld.display="none";
}
</script>
Any help would be greatly appreciated!
Use jquery, with code like:
$(document).ready(function(){
$('#pic1').attr('src','http://nyquil.org/uploads/IndianHeadTestPattern16x9.png');
});
With the html like:
<img id="pic1" />
It works by running when document's ready function is called (which is called after the DOM and other resources have been constructed), then it will assign the img's src attribute with the image's url you want.
Change the nyquil.org url to the image you want, and add as many as needed (just don't go overboard ;). Tested Firefox 3/chrome 10.
Here is the demo: http://jsfiddle.net/mazzzzz/Rs8Y9/1/
Working off your HTML structure I added a notifyLoaded class for the two images so you can watch for when both have loaded via an onload event. Since css background images don't get that event I've created a hidden img using the background's path so we can test when that image is loaded
HTML:
<div id="loading">
<img src="http://aaron-graham.com/img/parallax/ajax-loader.gif" border="0" />
</div>
<div id="vertical">
<div>
<div class="panel">
<img class="notifyLoaded" src="http://aaron-graham.com/img/parallax/tile3.png" />
</div>
</div>
</div>
<div id="imgLoader">
<img class="notifyLoaded" src="http://aaron-graham.com/img/parallax/deepspace3.jpg" alt="" />
</div>
You have reference to jQuery in your page already so I've replaced your script to the following.
jQuery:
$(document).ready(function() {
var $vertical = $('#vertical');
var $imgs = $('.notifyLoaded');
var imgCount = $imgs.length;
var imgLoadedCount = 0;
$vertical.backgroundparallax(); // Activate BG Parallax plugin
$imgs.load(function() {
console.log(this);
imgLoadedCount++;
if (imgCount == imgLoadedCount) {
// images are loaded and ready to display
$vertical.show();
// hide loading animation
$('#loading').hide();
}
});
});
I've also set #Vertical to a default display:none; which gets changed when images have loaded
CSS:
body {background-color:black;}
#loading {position:absolute;width:95%;text-align:center;top:300px;}
#vertical {display:none;background-image: url('http://aaron-graham.com/img/parallax/deepspace3.jpg');background-position: 0 0;height: 650px;width: 900px;overflow: auto;margin:35px auto auto auto;}
#vertical > div {margin: 0;color: White;}
#vertical .panel {padding: 100px 5%;margin-left:40px;height: 3363px;}
#imgLoader {display:none;}

Categories