Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to know if an element is rendered?

Tags:

javascript

css

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?

like image 274
BigName Avatar asked Apr 25 '15 18:04

BigName


2 Answers

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.

like image 188
Ankit Tanna Avatar answered Oct 17 '22 08:10

Ankit Tanna


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

like image 22
Useless Code Avatar answered Oct 17 '22 06:10

Useless Code