3

So I have some animations that need to happen before the page content shows up.

I'm using JS to hide the divs that I want to appear on load with an animation, but because the script file is being called after the HTML, the divs appear, disappear when the JS happens, and then appear again with the animation.

My problem is that when I put the script file in the beginning, the hiding doesn't happen, probably because the divs it's targeting don't exist yet.

Is there a way that I can load the jQuery file first and then hide the divs as soon as they exist but before they're finished loading?

PS: If I use css to hide the divs it won't work when javascript is disabled, which is a problem, and if I just use JS to switch classes I have the same problem with the delay, and it looks glitchy...

RPichioli
  • 3,245
  • 2
  • 25
  • 29
  • 1
    Could you not animate this using CSS animations? Also please include a [mvce](http://stackoverflow.com/help/mcve) – Bob Brinks Sep 21 '16 at 14:29
  • @BobBrinks no, i'm using this as an example but i need this for other things as well and those i can't use css for. – Suzanne Edelman Creoconcept Sep 21 '16 at 14:31
  • 1
    As you point out you have a trade off. you should either do it the "proper" way i.e. elements are shown by default for non-js users and then hidden for js users (rather then the other way around). Or you have to abandon the non-js users if you want a truly clean and slick experience. We need to see your code in order to help. – lharby Sep 21 '16 at 14:50

1 Answers1

3

Using the technique given here by I.devries, you can add the CSS style with Javascript code, in a script block that you can insert at the top of the HTML file:

<script type="text/javascript">
    var style = document.createElement('style');
    style.type = 'text/css';
    style.innerHTML = '.hiddenDiv { display: none; }';
    document.getElementsByTagName('head')[0].appendChild(style);
</script>

By applying the class to the divs, they will be hidden as soon as they load:

<div class="hiddenDiv" ... ></div>

In the case where Javascript is disabled, the style is not added and the divs are displayed.

Community
  • 1
  • 1
ConnorsFan
  • 70,558
  • 13
  • 122
  • 146