开发者

How to Hide DIVs, they are Showing for a Split Second on page Load

I have made a very quick jQuery slideshow, and I'm using this to hide the DIVs which shouldn't be shown until it's their turn:

$(document).ready(function() {
  //Hide All Div's Apart From First
  $('div#gall2').hide();
  $('div#gall3').hide();
  $('div#gall4').hide();

But on loading the page you can see DIV's gall2 gall3 and gall4 for a split second before they are hidden.

Would it be OK to just add inside my CSS:

#gall2, #gall3, #gall4{ display:none;}

This would solve开发者_JAVA技巧 the problem of them showing for a split second, just want to know if it's acceptable


Disabling in CSS is fine, but then users without JS will never see them.

To disable for users with JS only, mark the body and appropriate CSS:

<body>
  <script type="text/javascript">
    document.body.className += " js";
  </script>

CSS:

.js #gall2, .js #gall3, .js #gall4 { display: none; }


As an alternatie to orip's answer, you can do the following if you don't like adding scripts in the <body>:

<html>
<head>
  <script src="jquery.js"></script>
  <script>
    $('html').addClass('js');
    $(function() {
      // do DOM ready stuff
    });
  </script>
  <style>
  .js #gall2, .js #gall3, .js #gall4 { display: none; }
  </style>
</head>

You will avoid flickering this way because you are adding a class name to the HTML before DOM ready.


Yes, it's certainly acceptable to do it in your CSS

The other respondents are correct. It's not a good practice to make things only visible with JS. I guess I was just thinking technically : changing your CSS this way would solve the issue.


Always try to imagine what users who have JS turned off will see. If you use the CSS solution, the non-first DIVs will not be shown for them either, but if you change slides programmatically, they will see only the first one, obviously. It's best to give them a "No JS" option. Then, if you can be sure the user has JS enabled, you can hide the divs using CSS and show them using JS.


They are being shown because on default the divs are likely set to be shown. Since it can take a few seconds for the "ready" event to be fired on the page, the .hide() method calls won't hit until everything on the page is loaded and ready.

If I remember right the .hide() method will just set the "display" attribute of the element to "none". So by default setting the div to be hidden through CSS allows them to always be hidden, and you get the added bonus of users without JS not seeing them either.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜