I wanted to show a loading icon to users until the page elements are fully loaded. How can I do that with javascript and I want to do it with javascript, not jquery?
Here is a link how google does it
How can I do this?
triggering some function on onload event or something like this .. I know it will be done somewhat like this or any other ways to do it?
Or there is some event for it?
UPDATE
I did something using display property I hide the body element but and onload of body tag I change its property but where to put the loading icon and add more interactivity.
HTML
<body>
<div id="load"></div>
<div id="contents">
jlkjjlkjlkjlkjlklk
</div>
</body>
JS
document.onreadystatechange = function () {
var state = document.readyState
if (state == 'interactive') {
document.getElementById('contents').style.visibility="hidden";
} else if (state == 'complete') {
setTimeout(function(){
document.getElementById('interactive');
document.getElementById('load').style.visibility="hidden";
document.getElementById('contents').style.visibility="visible";
},1000);
}
}
CSS
#load{
width:100%;
height:100%;
position:fixed;
z-index:9999;
background:url("/loading.gif") no-repeat center center rgba(0,0,0,0.25)
}
Note:
you wont see any loading gif if your page is loaded fast, so use this code on a page with high loading time, and i also recommend to put your js on the bottom of the page.
DEMO
http://jsfiddle.net/6AcAr/ - with timeout(only for demo)
http://jsfiddle.net/47PkH/ - no timeout(use this for actual page)
update
http://jsfiddle.net/d9ngT/
The easiest way to put the loader in the website.
HTML:
<div id="loading"></div>
CSS:
#loading {
position: fixed;
width: 100%;
height: 100vh;
background: #fff url('images/loader.gif') no-repeat center center;
z-index: 9999;
}
JQUERY:
<script>
jQuery(document).ready(function() {
jQuery('#loading').fadeOut(3000);
});
</script>
add class="loading" in the body tag then use below script with follwing css code
body {
-webkit-transition: background-color 1s;
transition: background-color 1s;
}
html, body { min-height: 100%; }
body.loading {
background: #333 url('http://code.jquery.com/mobile/1.3.1/images/ajax-loader.gif') no-repeat 50% 50%;
-webkit-transition: background-color 0;
transition: background-color 0;
opacity: 0;
-webkit-transition: opacity 0;
transition: opacity 0;
}
Use this code
var body = document.getElementsByTagName('body')[0];
var removeLoading = function() {
setTimeout(function() {
body.className = body.className.replace(/loading/, '');
}, 3000);
};
removeLoading();
Demo: https://jsfiddle.net/0qpuaeph/
HTML, CSS, JS are all good as given in above answers. However they won't stop user from clicking the loader and visiting page. And if page time is large, it looks broken and defeats the purpose.
So in CSS consider adding
pointer-events: none;
cursor: default;
Also, instead of using gif files, if you are using fontawesome which everybody uses now a days, consider using in your html
<i class="fa fa-spinner fa-spin">
Element making ajax call can call loading(targetElementId) method as below to put loading/icon in target div and it'll get over written by ajax results when ready. This works great for me.
<div style='display:none;'><div id="loading" class="divLoading"><p>Loading... <img src="loading_image.gif" /></p></div></div>
<script type="text/javascript">
function loading(id) {
jQuery("#" + id).html(jQuery("#loading").html());
jQuery("#" + id).show();
}
HTML page
<div id="overlay">
<img src="<?php echo base_url()?>assest/website/images/loading1.gif" alt="Loading" />
Loading...
</div>
Script
$(window).load(function(){
//PAGE IS FULLY LOADED
//FADE OUT YOUR OVERLAYING DIV
$('#overlay').fadeOut();
});
firstly, in your main page use a loading icon
then, delete your </body> and </HTML> from your main page and replace it by
<?php include('footer.php');?>
in the footer.php file type :
<?php
$iconPath="myIcon.ico" // myIcon is the final icon
echo '<script>changeIcon($iconPath)</script>'; // where changeIcon is a javascript function whiwh change your icon.
echo '</body>';
echo '</HTML>';
?>
Related
http://www.chooseyourtelescope.com/ (>> Please watch it on a minimum 15'' screen, the site is not entirely responsive yet and you wont see what I'm talking about)
When you hover the buttons (moon, planet, etc...) it changes the background. But the transition is buggy on Chrome (image0>blank>image1). And worknig on IE11 but sometimes with a lag. I didn t try with the other browsers.
How to make a smooth transition?
A quick fade Image0>image1, not image0>transition color>image1
Here is the code for the MOON button. Thats the same with the others.
(I don't know anything about Javascript. I found the script below on Stackoverflow.)
HTML
<div class="top-logos-home" id="top-logos-moon-front"><img src="moon-logo.png" alt="MOON"></div>
CSS
.image-home {
position: absolute;
width: 100%;
height: 100%;
background-image: url(Frontpage.jpg);
background-size: cover;
display:inline;
top:0;
}
JAVASCRIPT
jQuery(function(){
var $body = $('.image-home');
$('#top-logos-moon-front').hover(function(){
$body.css('background-image', 'url("Frontpage-moon.jpg")')
}, function() {
$body.css('background-image', '')
})
})
You need to change just your script code if you want smooth transtion.
jQuery(function(){
var $body = $('.image-home');
$('#top-logos-moon-front').hover(function(){
$body.fadeOut('slow',function(){
$body.css('background-image', 'url("Frontpage-moon.jpg")').fadeIn('slow');
});
}, function() {
$body.css('background-image', '')
})
})
If you want to do best solution for this you need follow the steps below.
Firstly you need to defined your path of images in the js with the below code.
var imgs = [
'http://i.imgur.com/DwLjYhh.jpg',
'http://i.imgur.com/gAlqfUU.jpg'
];
After this step, you need to add new attiribute your buttons like data-id.
<div class="top-logos-home" id="top-logos-moon-front" data-id='0'>
<img src="button_image_jpg" alt="MOON">
</div>
When you defined all variables, you need to detect the hover with your current code and choose the right image that is in imgs array for your background.
jQuery(function(){
var $body = $('.image-home');
$('#top-logos-moon-front').hover(function(){
$body.fadeOut('slow',function(){
//fade out slowly element and after change the style of inner elements then fade in slowly.
$body.css('background-image','url('+imgs[$(this).attr('data-id')]+')').fadeIn('slow');
});
});
});
In my personal opinion; Image transitions shouldn't manage in this way. Create different element for each planets. When user click the button, planets slip and overlapping. You can see a demo in the below code.
http://codepen.io/thegeek/pen/GDwCa
I found a solution by using the opacity property. Now its working perfectly.
HTML
<img id="background-moon-front" class="hover-backgrounds" src="Frontpage-moon.jpg" />
CSS
.hover-backgrounds {
opacity:0;
transition: opacity 0.6s linear;
top:0;
position:absolute;
background-size: 100%;
}
JAVASCRIPT
$(document).ready(function (e) {
$("#top-logos-lune-front").hover(function (e) {
$("#background-moon-front").css("opacity", "1");
}, function() {
$("#background-moon-front").css("opacity", "0")
})
});
I've got a bunch of images, on click I want the images to turn white emulating some kind of fade effect. So you click it and for 1 second it fades from the original image to just white. I also need it to turn back to the original image when the user clicks something else.
Is this possible with JavaScript? - If so what should I be looking at (I'm really bad with graphics).
I've had a go at trying this with opacity but I don't want the background to be visible behind the image
Psuedo-element Solution
You could use a wrapper with a pseudo-element to overlay what you're looking for -- and the animations are handled by a toggled CSS class (which is ideal for performance).
CodePen Demonstration
HTML
<div class="whiteclicker">
<img src="http://lorempixel.com/400/200" alt=""/>
</div>
SCSS
#import "compass/css3/transition";
body { background: gainsboro; text-align: center; }
.whiteclicker {
display: inline-block;
position: relative;
&::after {
content: "";
display: block;
position: absolute;
top:0; left:0; right:0; bottom:0;
background: white;
opacity: 0;
#include transition(opacity 1s ease);
}
&.active::after {
opacity: 1;
}
}
JS
$('.whiteclicker').click(function(){
$(this).toggleClass('active');
});
To ameliorate the Spencer Wieczorek solution (the way two seems to be the best solution on my opinion) :
What about creating the white div on the fly (and fade it in and out) instead of put it in the html code ?
See the fiddle.
$("#myImage").click(function(){
$(this)
.parent().css({position:'relative'}).end()
.after($('<div>')
.hide()
.css({position:'absolute'
, top: $(this).position().top
, left: $(this).position().left
, width: $(this).width()
, height: $(this).height()
, background: '#FFF'
})
.fadeIn('fast')
.on({
click : function(e){
$(this).fadeOut('fast', function(){ $(this).remove();});
}
})
);
});
Then, you don't have anything to add to the html code or in the css styles, Jquery does everything.
#Spencer Wieczorek : I did my own answer, because I did not agree with your way of designing the css style (the fixed position is really not good, especially if the page is scrolled for example...). Mine is more ... standalone-y ;)
You might want to try having two images stacked on each other.
See this:
<script type="text/javascript">
var image1 = '<img class="images" src="Image 1" onClick="switch();" />';
var image2 = '<img class="images" src="Image 2" onClick="switch();" />';
var currentImage = 1;
function switch(){
if(currentImage==1){
currentImage++;
document.getElementById("image").innerHTML = image2;
}
if(currentImage==2){
currentImage--;
document.getElementById("image").innerHTML = image1;
}
}
</script>
<style>
.images{ position:fixed; top: 0; left: 0; }
</style>
<img class="images" src="Black image" />
<div id="image"><img class="images" src="Image 1" onClick="switch();" /></div>
For the fade I'm just gonna see how you could do it.
EDIT:
<script type="text/javascript">
var fadecount = 100;
function fade() {
document.getElementById("imageToFade").style.opacity = fadecount;
fadecount--;
if(fadecount==0){
clearTimeout(fade);
}
}
function start_fade(){
var fade = setTimeout(fade(), 10);
}
</script>
With Base 64 you can just have the binary version of the picture and then an all white picture and based on the .click you reassign the src to the white base64...
document.getElementById("img").src = "data:image/png;base64, iVBORw0KGgoAAAANSUhEUgAAAAUA
AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO
9TXL0Y4OHwAAAABJRU5ErkJggg=="
just change to the all white version after the click, technically js driven from click event, and doesn't involve two different elements existing just at different layers...
How do I display a loader when the page loads and hide it when it is loaded?
$(document).ready(function() {
$('.windowLoader').show().fadeOut(2000);
});
Displays the loader long after the page start loading and sometime the 2000 ms duration of the fadeOut event completed before the page has loaded.
Is there anyway to executed the display of the loader as soon as the DOM is ready and remain it visible until the page is loaded (not the images) and then hide the loader?
Why not put the loader directly in the document and then on ready remove it using jQuery? E.G.
<div id="loading"></div>
$(document).ready(function() {
$("#loading").fadeOut(function() {
$(this).remove(); // Optional if it's going to only be used once.
});
});
Else, if you're doing other things within your $(document).ready() then .fadeIn() (/show/create) your loading bar at the top of the method, do your extensive code, and then at the bottom call the .fadeOut()
As kindly suggested if you're worried about people without JavaScript viewing the loading bar then also add the following:
<noscript>
<style> #loading { display:none; } </style>
</noscript>
it should help
customize it according to your code
$(document).ready(function () {
// calculate height
var screen_ht = jQuery(window).height();
var preloader_ht = 5;
var padding = (screen_ht / 5) - preloader_ht;
jQuery("#preloader").css("padding-top", padding + "px");
// loading animation using script
function anim() {
jQuery("#preloader_image").animate({ left: '1px' }, 2000,
function () {
jQuery("#preloader_image"), animate({ left: '1px' }, 2000);
}
);
}
//anim();
});
function hide_preloader() {
// To apply Fade Out Effect to the Preloader
jQuery("#preloader").fadeOut(1000);
}
</script>
<style>
#preloader {background: #1c1c1c;position:fixed;left:0px; top:0px; width:100%; height:100%; text-align:center;color:#fff;z-index: 100000000;}
#preloader div {width:228px;height:240px;margin:auto;padding:10px 0;text-align:center;overflow:hidden;}
#preloader_image {width:228px;height:240px;position: relative;left:0px;top:-10px;}
</style>
</head>
<body id="home" onload="hide_preloader()">
<div id="preloader">
<div>
<div id="preloader_image">
<img src="loading.gif" style="position: absolute;bottom: 0;left: 35%;">
</div>
</div>
</div>
</body>
i have some very simple js (i'm still learning) that basically reads the elements of a form and creates a url string that is passed to an imaging server, that in turn renders the image.
var imgURL = "site.com/path/to/image";
var product = "BirthdayCard_End" + "?&";
var page = 2;
var format;
var data;
function setPage(inputID)
{
page = inputID;
setJPG();
}
function FormValues()
{
var str = '';
var elem = document.getElementById('form1').elements;
for(var i = 0; i < elem.length; i++)
{
str += "$" + elem[i].id + "=" + elem[i].value + "&";
}
data = str;
}
function genPDF()
{
var format = "fmt=pdf&mediaMargin=48&bleedMargin=48&printerMark=1,1,1,1,1,Illustrator,.25,1";
fullURL = imgURL + product + data + format;
window.open(fullURL);
}
function setJPG()
{
FormValues();
var format = "imageRes=200&fmt=jpg&wid=550&page=" + page;
fullURL = imgURL + product + data + format;
document.getElementById('lblValues').innerHTML = fullURL;
document.getElementById('image').src = fullURL;
}
i'm trying to figure out how to show a simple loader like this (http://fgnass.github.com/spin.js/#v1.2.5). how do I add something to the setJPG() function so that it pops up the loader everytime it is initialized, and then fades away once the image is loaded?
You guys are making this way more complicated than it needs to be. Put your image in a div and set the background of the div to be an animated gif.
<div style="background-image: url('spinner.gif')"><img src='bigImage.jpg'></div>
No need to use any JS at all, the image will simply load over the background spinner.
Suggested solution
For images, using a "loading spinner" is problematic. See below.
Instead of a spinner, first send a low resolution (consider B&W too) of the image. This SO question tells how.
Spinners for image loading
A problem with showing a spinner while you're waiting for an image to be displayed is that the browsers do not reliably tell your JS when the image has loaded.
And if it doesn't fire then you're left looking at the spinner forever...
See the docs for the jQuery load event --
Caveats of the load event when used with images
A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:
It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache
The easiest way to do it is to create two div one over the other.
One div with the spinner covering the div with the content, and then when the page finishes loading to display the div with the content over it.
On this example I use it on window.load, so you might need to modify the event to be on image load. The rest should work fine.
CSS:
#preloader {
position:absolute;
top:0;
left:0;
width:100%;
height:100%;
background:white;
opacity:0.3;
z-index:2;
}
#spinner_container {
position:absolute;
width:100%;
top: 50%;
left:0px;
height:1px;
overflow:visible;
opacity: 1;
background: transparent;
}
#spinner {
width: 31px;
height:31px;
margin-left:-15px;
position:absolute;
top:-15px;
left:50%;
display:block;
}
HTML
<div id="preloader">
<div id="spinner_container">
<img id="spinner" src="/content/images/spinner_squares_circle.gif" alt="" />
</div>
</div>
<div id="wrapper">
content
</div>
jQuery
$(window).load(function(){
$('#preloader').fadeOut(100, function() {
$('body').css('overflow','auto');
$(this).remove();
});
});
If you are using Spectre css, you can add this div to add a spinner :
<link href="https://cdnjs.cloudflare.com/ajax/libs/spectre.css/0.3.1/spectre.min.css" rel="stylesheet"/>
<div class="loading"></div>
I wrote loader code in a separate file so it will be reusable
file: Loader.js
export const elementString = {
loader:'loader' // class name that I used in renderLoader function
}
export const renderLoader = parent =>{
const loader = `
<div class='${elementString.loader}'>
<svg>
<use href="img/icons.svg#icon-cw"></use>
</svg>
</div>
`;
parent.insertAdjacentHTML('afterbegin', loader);
};
export const clearLoader=()=>{
const loader = document.querySelector(`.${elementString.loader}`);
if(loader){
loader.parentElement.removeChild(loader);
}
}
file: style.css
.loader {
margin: 5rem auto;
text-align: center; }
.loader svg {
height: 5.5rem;
width: 5.5rem;
fill: #F59A83;
transform-origin: 44% 50%;
animation: rotate 1.5s infinite linear; }
#keyframes rotate {
0% {
transform: rotate(0); }
100% {
transform: rotate(360deg); } }
file: icons.svg
<svg aria-hidden="true" style="position: absolute; width: 0; height: 0; overflow: hidden;" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<defs>
<symbol id="icon-cw" viewBox="0 0 20 20">
<title>cw</title>
<path d="M19.315 10h-2.372v-0.205c-0.108-4.434-3.724-7.996-8.169-7.996-4.515 0-8.174 3.672-8.174 8.201s3.659 8.199 8.174 8.199c1.898 0 3.645-0.65 5.033-1.738l-1.406-1.504c-1.016 0.748-2.27 1.193-3.627 1.193-3.386 0-6.131-2.754-6.131-6.15s2.745-6.15 6.131-6.15c3.317 0 6.018 2.643 6.125 5.945v0.205h-2.672l3.494 3.894 3.594-3.894z"></path>
</symbol>
</defs>
</svg>
file: app.js
renderLoader(document.querySelector('.results'));// .results is the parent of my searchlist which I am shoing in the view
await state.search.getResults();
clearLoader();
file: app.html
<body>
<div class="container">
<div class="results">
<ul class="results__list">
</ul>
</div>
</div>
</body>
Just add a spinning gif to the chart div, it will be replaced automatically by google chart when loaded. Like this,
""
How can I fade one image into another with jquery? As far as I can tell you would use fadeOut, change the source with attr() and then fadeIn again. But this doesn't seem to work in order. I don't want to use a plugin because I expect to add quite a few alterations.
Thanks.
In the simplest case, you'll need to use a callback on the call to fadeOut().
Assuming an image tag already on the page:
<img id="image" src="http://sstatic.net/so/img/logo.png" />
You pass a function as the callback argument to fadeOut() that resets the src attribute and then fades back using fadeIn():
$("#image").fadeOut(function() {
$(this).load(function() { $(this).fadeIn(); });
$(this).attr("src", "http://sstatic.net/su/img/logo.png");
});
For animations in jQuery, callbacks are executed after the animation completes. This gives you the ability to chain animations sequentially. Note the call to load(). This makes sure the image is loaded before fading back in (Thanks to Y. Shoham).
Here's a working example
$("#main_image").fadeOut("slow",function(){
$("#main_image").load(function () { //avoiding blinking, wait until loaded
$("#main_image").fadeIn();
});
$("#main_image").attr("src","...");
});
Well, you can place the next image behind the current one, and fadeOut the current one so that it looks like as though it is fading into the next image.
When fading is done, you swap back the images. So roughly:
<style type="text/css">
.swappers{
position:absolute;
width:500px;
height:500px;
}
#currentimg{
z-index:999;
}
</style>
<div>
<img src="" alt="" id="currentimg" class="swappers">
<img src="" alt="" id="nextimg" class="swappers">
</div>
<script type="text/javascript">
function swap(newimg){
$('#nextimg').attr('src',newimg);
$('#currentimg').fadeOut(
'normal',
function(){
$(this).attr('src', $('#nextimg').attr('src')).fadeIn();
}
);
}
</script>
Are you sure you're using the callback you pass into fadeOut to change the source attr and then calling fadeIn? You can't call fadeOut, attr() and fadeIn sequentially. You must wait for fadeOut to complete...
Old question but I thought I'd throw in an answer. I use this for the large header image on a homepage. Works well by manipulating the z-index for the current and next images, shows the next image right under the current one, then fades the current one out.
CSS:
#jumbo-image-wrapper
{
width: 100%;
height: 650px;
position: relative;
}
.jumbo-image
{
width: 100%;
height: 100%;
position: absolute;
top: 0px;
left: 0px;
}
HTML:
<div id="jumbo-image-wrapper">
<div class="jumbo-image" style="background-image: url('img/your-image.jpg');">
</div>
<div class="jumbo-image" style="background-image: url('img/your-image-2'); display: none;">
</div>
</div>
Javascript (jQuery):
function jumboScroll()
{
var num_images = $("#jumbo-image-wrapper").children(".jumbo-image").length;
var next_index = jumbo_index+1;
if (next_index == num_images)
{
next_index = 0;
}
$("#jumbo-image-wrapper").children(".jumbo-image").eq(jumbo_index).css("z-index", "10");
$("#jumbo-image-wrapper").children(".jumbo-image").eq(next_index).css("z-index", "9");
$("#jumbo-image-wrapper").children(".jumbo-image").eq(next_index).show();
$("#jumbo-image-wrapper").children(".jumbo-image").eq(jumbo_index).fadeOut("slow");
jumbo_index = next_index;
setTimeout(function(){
jumboScroll();
}, 7000);
}
It will work no matter how many "slides" with class .jumbo-image are in the #jumbo-image-wrapper div.
For those who want the image to scale according to width percentage (which scale according to your browser width), obviously you don't want to set height and width in PIXEL in CSS.
This is not the best way, but I don't want to use any of the JS plugin.
So what can you do is:
Create one same size transparent PNG and put an ID to it as
second-banner
Name your original image as first-banner
Put both of them under a DIV
Here is the CSS structure for your reference:
.design-banner {
position: relative;
width: 100%;
#first-banner {
position: absolute;
width: 100%;
}
#second-banner {
position: relative;
width: 100%;
}
}
Then, you can safely fade out your original banner without the content which placed after your image moving and blinking up and down