Onload function runs before loading of all elements - javascript

I have a div on my page which I want to show after all elements (scripts, pictures and so on) finish loading. But it seems that the onload function doesn't work as I can see the page before everything is loaded. I have only one js file linked to my page, and below I showed how I organized the code (hope its a right way). I have also put a broken img link to the page, to test if the function executes without the missing file, and it does.
HTML
<div id="dvLoading"></div>
CSS
#dvLoading{
position: fixed;
height: 100%;
width: 100%;
top: 0;
background: red;
z-index:9999;
}
JQuery
var onLoad = function(){
$(window).load(function(){
$('#dvLoading').fadeOut(500);
});
}
var someFunction1 = function(){
//some function
}
var someFunction3 = function(){
//some function
}
var someFunction3 = function(){
//some function
}
$(document).ready(function(){
onLoad();
someFunction1();
someFunction2();
someFunction3();
});

Try this instead :
$( window ).load(function() {
$('#dvLoading').show().delay(3000).queue(function(n) {
$(this).fadeOut("slow").delay(1000); n();
});
});
CSS
#dvLoading{
display: none;
position: absolute;
height: 100%;
width: 100%;
top: 0;
background: red;
z-index:9999;
}
Your issue could be that you're trying to call a function which fires onload within a document.ready wrapper.
EDIT
This will show the hidden div and delay the fadeout for however long you need once all resources have loaded.
EXAMPLE
JS FIDDLE

Related

Click on link to show page loader, then make page loader disappear after a defined time, the show destination's url

I'm quite new concerning javascript and I have a problem that seems too simple but it's giving me trouble.
I have a link and I want to achieve that when I click on the link, an invisible page loader appears, then I want the page loader to disappear after a determined amount of time, and finally that it goes to the url of the link.
It's important that it happens on the page before, I don't want the div to be shown onload.
I've tried several extra scripts "setTimeout", "prevent" to hide the loader after a while but it doesn't work... it simply disappears as soon as the page finishes loading.
This is so far the cleanest point I've come to.
<a class="#" href="#" onclick="javascript:document.getElementById('page-loader').style.display='block';"></a>
#page-loader {
position: absolute;
top: 0;
bottom: 0%;
left: 0;
right: 0%;
z-index: 10000;
display: none;
text-align: center;
width: 100%;
padding-top: 250px;
background-color: black;
}
I hope you can help me out with this
You're pretty much on track! When you click a link, you'll need to show the loader div. You've got the CSS defined, and just need to modify the display value to show it (either through style.display or applying another class which overrides the display: none).
Using setTimeout, you can then define a callback to hide the div and navigate.
Here's an example (hides loader after a second, and then navigates after a half second):
// Bind our our click event listener
document.querySelector('a').addEventListener('click', function (e) {
// Calling preventDefault will prevent the browser from navigating (prevents the default behavior)
e.preventDefault();
// Our defined link, where we want to navigate to
const destination = this.getAttribute('href');
// Our loader div - we'll set to a const to reference later
const loader = document.querySelector('#page-loader');
// On click, we immediately want to show our loading div.
// For this demo, we'll use style.display to override our CSS
loader.style.display = 'block';
// Set Timeout - We've defined a 1 second delay
setTimeout(function () {
// After 1 second, we want to hide the loader. Again, using style, we set to 'none'
loader.style.display = 'none';
// One additional set timeout - this allows the browser time to hide the loader. I've defined a half second
setTimeout(function () {
// This will set the URL to our href
window.location.href = destination;
}, 500);
}, 1000);
})
#page-loader {
position: absolute;
top: 0;
bottom: 0%;
left: 0;
right: 0%;
z-index: 10000;
display: none;
text-align: center;
width: 100%;
padding-top: 250px;
background-color: black;
}
<div id="page-loader">Loading</div>
Google
One suggestion: I would avoid using href="#" as a way to avoid navigating. Call e.preventDefault to prevent the browser from immediately navigating to the destination. That way, if JavaScript is disabled/blocked or broken, the link will still work.
Happy learnings!
Try this
const nav = () => {
var loader = document.getElementById('loader');
loader.style.display='block';
setTimeout(()=>loader.style.display = 'none', 3000);
}
#loader{
display: none;
}
<div id='loader'>Loading...</div>
<a href='#' onClick='nav()'>Change</a>
try this
<script>
document.getElementById("page-loader").addEventListener("click", function(event){
event.preventDefault();
document.getElementById("page-loader").style.display='block';
});
<script>

Load overlay till page is rendered

I am trying to make it so that there is an overlay on the page till the page is fully rendered. I can do this by using timeouts but that is probably not the right way to do this. Is there a better way to achieve this?
Issue I am having is that $(window).load doesn't trigger.
JS:
$(document).ready(function() {
$(".overlay").fadeIn();
$(window).on('load', function() {
$(".overlay").fadeOut();
});
});
CSS:
.overlay{
display: none;
position: fixed;
padding: 0;
margin: 0;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0, 0, 0, .3);
opacity: .8;
pointer-events: none;
}
JSFiddle Demo
jQuery's document.ready event is fired asynchronously and hence may fire after the window.load event in some cases.
https://github.com/jquery/jquery/issues/3197
https://github.com/jquery/jquery/issues/1823
https://github.com/jquery/jquery/issues/3447
This happens e.g. in your fiddle, because there is almost nothing on the page to load.
Your fiddle can be fixed using this js and setting the Load Type of the js to "No wrap - in < body >":
$(".overlay").fadeIn(function(){
console.log('fadedin');
});
$(window).on('load', function(){
$(".overlay").fadeOut(function(){
console.log('fadedout');
});
});
Try also:
$(document).ready(function(){
$(".overlay").fadeIn(function(){
console.log('fadein');
});
});
$(window).on('load', function(){
$(".overlay").fadeOut(function(){
console.log('fadedout');
});
});
to see that the document.ready event is fired after the window.load event.
This will help you. First document is loaded then window is loaded.
$(document).ready(function() {
$(".overlay").fadeIn();
});
$(window).on('load', function() {
$(".overlay").fadeOut();
});
For more ref -
http://javarevisited.blogspot.in/2014/11/difference-between-jquery-document-ready-vs-Javascript-window-onload-event.html?m=1

Display loader on load event and remove the loader when background image is loaded

I have two divs.
1 : where background image is loaded
2 : where loader gif is loaded.
what I want is , when there is a window.load() event is called then loader gif should displayed , and when background image is fully loaded , then loader gif should be removed. that's what I want to achieve.
$(window).load(function (){
$('.background_image_div').load(function(){
$('.gif_loader_image').hide();
});
});
// this code is not working.
.background_image_div{
background: url(http://www.banneredge.com/images/portfolio.jpg);
width: 600px;
height: 300px;
margin: 0 auto;
border: thin black solid;
z-index: 900;
}
.gif_loader_image{
position: absolute;
width: 50px;
height: 50px;
background: url(https://media0.giphy.com/media/3oEjI6SIIHBdRxXI40/200_s.gif);
// border: thin red solid;
left: 55%;
bottom: 15%;
z-index: 1001;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gif_loader_image"></div>
<div class="background_image_div">
</div>
Thank you.
instead of $(window).load(function (){ do a $( document ).ready(function() { as,
$( document ).ready(function() {
// Handler for .ready() called.
$('.background_image_div').load(function(){
$('.gif_loader_image').hide();
});
});
EDIT Caveats of the load event when used with images as taken from here, .load API
EDIT 2 try a poller, keep polling and check for the image inside the div using .length > 0. Do some changes to your html,
Keep a div and then an image tag inside it with this structure, <div id="backgroundImageDiv"><img src="whatEverTheURLIs" id="backgroundImageID"></div>
Inside your poller check if $("#backgroundImageDiv > #backgroundImageID").length() > 0
If the condition satisfies, hide the gif loader using .hide(). Check for the syntaxes please.
By poller I mean an interval timer.
You can do as like this way.
Just see this link
<div class="feature"><div class="loader"><img src="http://www.ajaxload.info/cache/FF/FF/FF/00/00/00/1-0.gif"></div></div>
$(function(){
var bgimage = new Image();
bgimage.src="http://cdn.wonderfulengineering.com/wp-content/uploads/2016/01/nature-wallpapers-10.jpg";
$(bgimage).load(function(){
$(".feature").css("background-image","url("+$(this).attr("src")+")").fadeIn(2000);
$(".loader").hide();
});
});
http://jsfiddle.net/n4d9xxon
You can try like this :
$(document).ready(function (){
$('.gif_loader_image').fadeOut(1000);
});
body{
background: url(http://www.banneredge.com/images/portfolio.jpg);
width: 100%;
height: auto;
}
.gif_loader_image{
position: fixed;
width: 100%;
height: 100%;
left: 0px;
bottom: 0px;
z-index: 1001;
background:rgba(0,0,0,.8);
text-align:center;
}
.gif_loader_image img{
width:30px;
margin-top:40%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="gif_loader_image">
<img src="https://media0.giphy.com/media/3oEjI6SIIHBdRxXI40/200_s.gif" alt="Loader..."/>
</div>
<div class="background_image_div"></div>
The main problem is that your $(window).load doesn't even fire
Why
This won't work since the .load() method was fully removed by jQuery 3 and since you are working with the version 3.1.1 it's not a surprise that your code doesn't work. You have to use now the .on() method to achieve the same effect
So
$(window).load(function (){
$('.background_image_div').load(function(){
$('.gif_loader_image').hide();
});
});
would turn into
$(window).on('load', function (){
$('.background_image_div').on('load', function(){
$('.gif_loader_image').hide();
});
});
Notice
Since you have already the $(window).load function at the beginning you don't have to define it again for your background image because this method will only be fired when all images are fully loaded so I think in your case this should also do the job.
jQuery
$(window).on('load', function () {
$('.gif_loader_image').hide();
});

Detect dynamically created elements in JavaScript

I am trying to create a box that expands and collapses using regular JavaScript (No jQuery). The problem I'm running into is detecting how to properly detect dynamically created elements or classes that are added to elements after pageload.
Here's an example JS fiddle page:
http://jsfiddle.net/1a518a4t/3/
As you can see, it works when you collapse and then expand once, but then it won't collapse again.
JS code:
function test() {
var badge = document.getElementById('test');
var close_button = document.querySelector('.test-close');
close_button.addEventListener("click", close_box);
function close_box() {
badge.style.bottom = '-70px';
close_button.classList.add("test-open");
close_button.classList.remove("test-close");
var open_button = document.querySelector('.test-open');
open_button.addEventListener("click", open_box);
}
function open_box() {
badge.style.bottom = '0';
close_button.classList.remove("test-open");
close_button.classList.add("test-close");
}
}
window.onload = test;
I think I really just want to learn how to replicate jQuery's on method in JavaScript. That works for elements that are dynamically created after pageload.
Use a single event listener. And don't modify inline styles, just switch classes:
var badge = document.getElementById('test');
var button = document.querySelector('.button');
button.addEventListener("click", function toggle_box() {
badge.classList.toggle('opened');
badge.classList.toggle('closed');
});
#test {
width: 300px;
height: 100px;
background-color: #ccc;
position: fixed;
bottom: 0;
right: 20px;
transition: all 0.2s;
}
#test.closed {
bottom: -70px;
}
#test > .button {
position: absolute;
top: 10px;
right: 10px;
width: 10px;
height: 10px;
text-indent: -9999px;
cursor: pointer;
background-color: #000;
}
#test.closed > .button {
background-color: #CE312F;
}
<div id="test" class="opened">
<div class="button">Test</div>
</div>
As mentioned in the comments, this is because the created element is added dynamically and as such you need to delegate so event handler can bind it to the created element. To do that you can look at #Ramswaroop solution to do this in native JavaScript. Although I don't think it's even nessisary to change class and re-bind the different functions. Simply use the same <div> and have a toggle function:
var button = document.querySelector('#test div');
button.addEventListener("click", toggle_box);
...
function toggle_box() {
if(badge.style.bottom == '-70px') {
badge.style.bottom = '-0';
toggleClass("test-close", "test-open");
} else {
badge.style.bottom = '-70px';
toggleClass("test-open", "test-close");
}
}
Fiddle Example

How to preload a webpage before showing it?

I have created a simple webpage with several images, but when a user visits it, the browser loads the images one at a time, instead of all at once.
I want instead to first show a "loading" gif in the center of the page and then, when all the images are downloaded, show the entire webpage to the user at once..
How can I do this?
You can show a loader image by putting it somewhere im <img> tag and use below js code to hide it later on when all images are shown:
window.onload = function(){
var el = document.getElementById('elementID');
el.style.display = 'none';
};
Where elementID is supposed to be the id of loader element/tag.
The load event fires when all images/frames/external resources are loaded, so by the time that event fires, all images are loaded and we therefore hide the loading message/image here.
Edit: I defer to Keltex's answer. It's a much better solution. I'll leave mine here for posterity (unless I should delete the content and my answer entirely? I'm new here).
Another solution, which was used fairly frequently in the past, is to create a landing page that preloads all of your images. When the preloading is done, it redirects to the actual site. In order for this to work, you'd need to get the URLs to all of the images you want to load, and then do something like this:
# on index.html, our preloader
<script type='text/javascript'>
// add all of your image paths to this array
var images = [
'/images/image1.png',
'/images/image2.png',
'/images/image3.png'
];
for(var i in images) {
var img = images[i];
var e = document.createElement('img');
// this will trigger your browser loading the image (and caching it)
e.src = img;
}
// once we get here, we are pretty much done, so redirect to the actual page
window.location = '/home.html';
</script>
<body>
<h1>Loading....</h1>
<img src="loading.gif"/>
</body>
You can do this with JQuery. Say your page looks like this:
<body>
<div id='loader'>Loader graphic here</div>
<div id='pagecontent' style='display:none'>Rest of page content here</div>
</body>
You can have a JQuery function to show pagecontent when the entire page is loaded:
$(document).ready(function() {
$(window).load(function() {
$('#loader').hide();
$('#pagecontent').show();
});
});
HTML
<div id="preloader">
<div id="loading-animation"> </div>
</div>
JAVASCRIPT
<script type="text/javascript">
/* ======== Preloader ======== */
$(window).load(function() {
var preloaderDelay = 350,
preloaderFadeOutTime = 800;
function hidePreloader() {
var loadingAnimation = $('#loading-animation'),
preloader = $('#preloader');
loadingAnimation.fadeOut();
preloader.delay(preloaderDelay).fadeOut(preloaderFadeOutTime);
}
hidePreloader();
});
</script>
CSS
#preloader {
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 9999;
position: fixed;
background-color: #fff;
}
#loading-animation {
top: 50%;
left: 50%;
width: 200px;
height: 200px;
position: absolute;
margin: -100px 0 0 -100px;
background: url('loading-animation.gif') center center no-repeat;
}
Create a div with class name preloader and put a loader inside that div.
style the class preloader just like below
.preloader {
position: fixed;
top: 0px;
left: 0px;
width: 100%;
height: 100%;
background-color: white;
/* background-color is would hide the data before loading
text-align: center;
}
Html
<div class="preloader">
Any loader image
</div>
Jquery
$(window).load(function(){
$('.preloader').fadeOut(); // set duration in brackets
});
A simple page loader is ready....

Categories

Resources