Search code examples
jqueryhidedelay

Why is jQuery hide not immediate (delayed by page load)


What I have:

I'm using jQuery to hide the last few list items in an unordered list.

My problem:

The list items appear on the page until the page loads and the jQuery kicks in (which is undesirable).

EDIT: I cannot edit the HTML. Since I can't selectively add classes I can therefore not rely on pure CSS. I'm using a jQuery selector to target the last two list items.

My code:

Whether I use the hide() function or addclass() + display:none, I experience the same problem.

<ul id="some_menu">
    <li><a href="#">Enkidu</a></li>
    <li><a href="#">Gilgamesh</a></li>
    <li><a href="#">Epic</a></li>
    <li><a href="#">Sumeria</a></li>
    <li><a href="#">Anunnaki</a></li>
</ul>

<script type="text/javascript">
    jQuery(document).ready(function() {
        //jQuery('ul#some_menu li:gt(2)').addClass("hide_menu_link");
        jQuery('ul#some_menu li:gt(2)').hide();
    });
</script>

<style type="text/css">
    .hide_menu_link{
        display:none;
    }
</style>

Here's the code on JSFIDDLE though it doesn't reproduce the problem: http://jsfiddle.net/dominornovus/pB8Mb/2/


Solution

  • By using jQuery(document).ready you are telling jQuery to wait for the document to be ready before executing. So, it will, indeed, wait for the page to be ready (loaded) before it takes action.

    Like others said, if you want some items to be hidden at page start and some other to be available, you should reverse the logic, start with everything hidden and then show want you want to display when the document is ready.