I want to zoom out to 85 % before the page is fully loaded. Now the code has a problem that the zoom only works if the page is fully loaded.
I try to put it to the head of html, but it doenst works.
Can you help me?
Here is my code:
window.onload = function zoom(){ document.body.style.zoom = "85%" }
Place this just after the opening body tag.
<script>
document.body.style.zoom = "85%";
</script>
Without the code being wrapped in a function that is a callback to the window.onload event, it will execute as soon as it is encountered.
You can use DOMContentLoaded event. It is fired when the document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.
For example
document.addEventListener('DOMContentLoaded', () => {});
Thanks very much. It works but somehow I have to wait until the page is fully load, then I can see that it zoom out to 85 %. So the picture looks like it jumping.
document.addEventListener('DOMContentLoaded', () => {});
Related
I am doing maintenance work for a website. The logo on the home page is supposed to bounce in from left after page has loaded but the animation begins even when the page is still loading.
The code is
$(document).ready(function(){
$('#logo-large').addClass('animated bounceInLeft');
});
The site is using animate.css library
The ready method do not wait for resources to load.
While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.
Reference: https://api.jquery.com/ready/
Use window.load method:
The load event is sent to an element when it and all sub-elements have been completely loaded. This event can be sent to any element associated with a URL: images, scripts, frames, iframes, and the window object.
$(window).on('load', function() {
$('#logo-large').addClass('animated bounceInLeft');
});
Reference: https://api.jquery.com/load-event/
The problem here is that you say "page loaded" but you haven't defined what that means. The animation is, indeed, playing after the DOM has loaded. That's what the $(document).ready method insures. However, any images or asynchronous calls can still trigger after the DOM is ready. So... the REAL question is, do you want to wait til after the images have loaded AND do you have any asynchronous calls that need to be accounted for.
I just wrote this so I'm not 100% sure if it doesn't have any bugs, but this should work for both cases.
jQuery.prototype.pageComplete = function(promises, callback){
if(!callback){
callback = promises;
promises = [];
}
var images = jQuery.Deferred();
var DOMReady = jQuery.Deferred();
var count = this.length;
promises.push(images);
promises.push(DOMReady);
jQuery(document).ready(function(){
DOMReady.resolve();
});
function counter(){
if(--count == 0) images.resolve();
}
this.each(function(image){
var img = new Image();
img.onload = counter;
img.src = image.src;
});
jQuery.when.apply(jQuery, promises).then(callback);
};
You use it like so:
// for just images
$('img').pageComplete(function(){
// code to transition image here
});
// for images and ajax
$('img').pageComplete([
ajax1, // these are all promises created by jQuery.ajax
ajax2,
ajax3
],
function(){
// code to transition image here
});
Try this one, solution should work without jquery
window.onload = function() {
document.getElementById('logo-large').classList.add('animated', 'bounceInLeft');
};
Use The Window Load Function
This will wait until the whole page has loaded before running the animation
jQuery(window).load(function() {
$('#logo-large').addClass('animated bounceInLeft');
});)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
My element has transition: transform .5s
then it has a separate class: transform: translatex(-100%)
So what I would like to achieve is that initially, the element is positioned towards the left. At window onload,When the element is rendered, I remove the transform class, and the browser would animate the element back to its correct position.
But what actually happens is that when the page becomes visible/rendered, the element is already at the correct position. and there is no animation.
I tried setTimeout(function() {}, 0); it doesn't work. If I setTimeout for 1 second, it works, but sometime rendering takes long, and I have to setTimeout for 2 seconds. But then sometimes it renders fast, and 2 seconds is a long time to wait.
So overall, I feel this is not a reliable or a correct way of doing this.
How can I achieve what I want, the correct way?
Edit:
Sorry guys, after trying to put together a demo, I realized I wasn't removing the class at window onload. This is because my element and its javascript and css are loaded with AJAX. So it can happen before the window onload or after the window onload.
Anyway, now my question is, what if the window takes a long time to load? Could it be possible that my element would be rendered before window finishes loading? Or does browsers only render when the entire window finishes loadings?
Because I want to animate the element as soon as possible. So, is it safe to wait for window onload, in the case that window takes a long time to load(images and slow connection, and stuff)?
And if I load the element with AJAX after the window loads, could I immediately run the animation by removing the transform? Or should I detect for when the element is rendered?
You might want to try using a combination of the DOMContentLoaded event and requestAnimationFrame. DOMContentLoaded fires after the document has been completely loaded and parsed but before all of the images and other assets on the page have completed downloading. requestAnimationFrame will delay the removal of the class until after the page has been painted so the element will properly transition.
var box = document.getElementById('box'),
showBox = function (){
box.classList.remove('offscreen');
};
document.addEventListener("DOMContentLoaded", function(event) {
window.requestAnimationFrame(showBox);
});
jsfiddle
You should use DOM Content Loaded event of javascript
document.addEventListener("DOMContentLoaded", function(event) {
console.log("DOM fully loaded and parsed");
});
This will be fired only when your entire content is loaded and parsed fully by your browser.
Don't consider this an answer as I am sure you can find something more elegant, but this may give you some ideas.
Add this to the javascript AJAXed in - be sure to wrap the javascript in a document.ready:
$(function(){
var giveup = 0; //in case something goes wrong
var amirendered = 0;
while (amirendered==0){
setTimeout(function(){
if (element.length){
amirendered = 1;
$('#myElement').addClass(doTransition);
}
},200);
giveup++;
if (giveup>200) amirendered++; //prevent endless loop
}
}); //END document.ready
I would like attach a function to window.onload so that it executes after everything is load. I have tried to do:
window.addEventListener('load', myFunction ,false);
window.onload = myFunction;
window.attachEvent('onload', myFunction); (this way does not work on Chrome)
What happens to me is that this function, looking at the Chrome's console (Network tab) is executed before window.onload (before the red line). I know this, because myFunction tries to load a remote javascript file and this file is loaded before red line.
I have also tried something more simple:
$(function() {
console.log("1111111");
});
window.onload=console.log("222222);
The output of that is:
22222222222
11111111111
Why ??? The first part should execute after DomContentLoaded and the second one after window.load isnt it? So why is this happening?
// This way does not work in Chrome
That's because you're using onload instead of load.
I've heard about the onload function which is called after the element is fully loaded.
In the case of graphics or images, does that mean it will wait until the image is displayed in the browser?
<body onload="foo()">...
<img onload="bar();"....
If not, is there a way to get the event when all graphics are drawn and images are displayed on a page?
In my case it´s only one 1600*1200 jpeg image and i draw on it. But the image has to be displayed before i start drawing, even with the onload event i see the drawed lines before the image appear.
Yes body onload will wait until all images (and other content) are loaded/displayed in the browser. The img onload will wait until that specific image has loaded/is displayed
Images have a complete property that's true when they are loaded.
e.g. would test if everything has loaded:
var allImagesLoaded = true;
$("IMG").each(function(){ allImagesLoaded &= $(this).attr("complete"); });
if(allImagesLoaded){ alert("Done!");}
Images raise a load event once they've finished loading
why dont you keep a counter for your images that will decrement by one on each image load.
check if it equal to 0 then call some another function.
in this way you can do the thing you want to when all images are loaded
$(function() {
$('img').one('load',function() {
// fire when image loads decrement the counter
if counter ==0
fireanotherfunction()
});
});
by above code u can attain your purpose
When reading the jQuery ready API documentation here:
While JavaScript provides the load event for executing code when a
page is rendered, this event does not get triggered until all assets
such as images have been completely received.
So onload is launched after everything has been loaded (and displayed).
See the window.load event:
The load event fires at the end of the document loading process. At this point, all of the objects in the document are in the DOM, and all the images and sub-frames have finished loading.
This is exact what you want, I believe.
JQuery's $(document).ready is not what you want:
In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event [instead of the ready event].
If you're using plain JS, window.load is what you want.
If you are using jQuery, you'll want $(document).load.
try jquery ready function
$(document).ready(function(){
bar();
});
I'm not sure if it works, but it's a try :D
I have the same problem developing a web view for an Android app. The load events (both for window and image element) as well as the complete state of the image element fire too early. My (svg) image has not yet finished drawing and thus calculations on the size go wrong.
The only workaround that I have found is a very short timer (1ms or maybe 10ms). That works for me because I have only one such image to consider. And since I start this timer when the image data has already loaded, this short lapse should be long enough for the device to paint the image.
window.addEventListener('load', function() {
var img = document.getElementById('logo');
window.setTimeout(function(){
var imgRatio = img.naturalWidth / img.naturalHeight;
var renderedWidth = parseInt(window.getComputedStyle(img).width.match(/(\d+)px/));
console.log(renderedWidth, img.complete);
if (renderedWidth < img.naturalWidth) {
img.style.height = (renderedWidth / imgRatio) + 'px';
}
}, 1);
}
Instead of the window load event, the image's load event should also work. But I found it safer to wait for everything, because other elements might affect the drawing of my image.
I have a javascript code like this
<script type="text/javascript">
window.onload=myFunction;
</script>
Is there any difference in using the above snippet in the <head></head> tag and just before
</body> tag, as I would like to call my function after the page loads.
basically there's no pratical difference, but I recommend
to place that code at the bottom, since you need to use a script (blocking-rendering tag) it's better put it at the end of the document.
to avoid a destructive assignments like that: writing window.onload=myFunction you destroy other previous assignments to window.onload event (if any) so it's better something like
(function() {
var previousOnLoadIfAny = window.onload;
window.onload = function() {
if (typeof previousOnLoadIfAny === 'function') {
previousOnLoadIfAny();
}
yourfunction();
}
}());
Binding to window.onload will always run your function when the load event fires. This only fires after everything in the page has finished loading, including images etc. If you want to run your function when the DOM has finished loading but before everything else then you can bind to the DOMContentLoaded event or use a library like jQuery (e.g. $(function(){ myFunction() });).
The benefit about putting your function at the end of your <body> is that theoretically this means that the rest of your content has already loaded and you don’t need to bind your function to a load event. This sometimes works, but depends on the situation.
No, where you place that will not matter - anywhere in the document and it will trigger when the document and all external resources (images, scripts etc) has loaded.
Because onload triggers after all external resources one often want to use DOMContentLoaded instead which triggers when the HTML DOM is ready. Which will make for a page that is more responsive.