dotnetnoob
dotnetnoob

Reputation: 11330

Div showing before slidedown when using javascript

I have an issue with a Div that is temporarily shown before, sliding into view.

The Div should be visible if no javascript is available and start hidden if javascript is available. I use css and javascript.

.no-js .show {
    display:block
}

$('body').removeClass('no-js').addClass('js-ok');

However, I want to slide the div in rather than just show it. Here's the code:

$('#site-cookie-notice').slideDown();

The result is that the div temporarily shows (via the css), before being hidden, then re-displayed with javascript.

Any ideas as to how this could be worked around?

Upvotes: 0

Views: 53

Answers (2)

Wil
Wil

Reputation: 5057

I guess you're using doc.ready? You need to use blocking JS like Modernizr does to replace your no-js class in the head. That way it'll be hidden when it's first rendered. Modernizr does it in the head thus:

var docElement = document.documentElement;
docElement.className = docElement.className.replace('no-js', 'js-ok');

Upvotes: 1

Adam Jenkins
Adam Jenkins

Reputation: 55613

Yes.

  1. Put the code that adds/removes the js class in the head
  2. DO NOT put it inside a $(document).ready() like so many people do.
  3. Put the classes of no-js and js-ok on your HTML, instead of your body (your body element won't be available when your code gets executed)

If you do it like this, then the classes will get applied to the HTML element before the rest of the page is rendered (meaning your .no-js .show CSS rule will never get applied).

Like this:

<!doctype html>
<html class="no-js">
 <head>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js></script>
  <script>
    $('html').removeClass('no-js').addClass('js-ok');
  </script>
 </head>
 <body>
   ...
 </body>
</html>

Upvotes: 0

Related Questions