Ferhat
Ferhat

Reputation: 303

jQuery dropdown menu on page load

If there are sub-categories under my main category, I add drop-down arrows for them. However, when I refreshed the page, I sometimes ran into the issue of arrows arriving late and delaying the loading of the page. Is there a way to prevent late loading?

$(document).ready(function() {
  $('.cat-parent')
    .prepend("<span style='float:right;cursor:pointer' class='show'></span>")
    .click(function() {
        
        $(this).find('ul.children').slideToggle(300).toggleClass('ok');

    });
});
body{
width:180px;
}
ul.children {
  display: none;
}

ul.children.ok {
  display: block;
}

.show{
    position: relative;
    width: 10px;
    height: 10px;
    border-right: 0.1em solid black;
    border-top: 0.1em solid black;
    transform: rotate(133deg);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<ul class="product-categories">
  <li class="cat-item cat-item-16 cat-parent"><a href="#">Clothing</a>
    <ul class="children">
      <li class="cat-item cat-item-19"><a href="#">Accessories</a></li>
      <li class="cat-item cat-item-18"><a href="#">Hoodies</a></li>
    </ul>
  </li>
<br>
<li class="cat-item cat-item-21"><a href="#">Test</a>
    <ul class="children">
      <li class="cat-item cat-item-39"><a href="#">TEST</a></li>
    </ul>
  </li>
  
 
 <br> 
  <li class="cat-item cat-item-15 cat-parent"><a href="#">Uncategorized</a>
    <ul class="children">
      <li class="cat-item cat-item-39"><a href="#">Example</a></li>
    </ul>
  </li> 
</ul>

Upvotes: 0

Views: 118

Answers (1)

Greg
Greg

Reputation: 4518

You're loading the arrows with the following code .prepend("<span style='float:right;cursor:pointer' class='show'></span>")

For this to display, the code is doing the following:

  1. Download html, css & JS files
  2. Render the html
  3. Run the JS code
  4. Wait for the JQuery in the CDN to intialise $(document).ready(function()
  5. Then append the html

Usually this happens so quickly it appears almost instantly. However there can be slowness due to accessing the CDN or the web browser running the code.

Anyway there are generally 2 approaches:

  1. Move html from JavaScript code and place it in the html.
  2. Hide the html on page load using css and once JQuery has loaded show the page. For Example:

<body class="hide"></body>

.hide { display:none;}

$(document).ready(function() {
    $('.cat-parent').prepend("<span style='float:right;cursor:pointer' class='show'></span>")
    $('.hide').fadeIn(1000)      
});

Heres a demo: https://jsfiddle.net/jecad9fw/3/

Upvotes: 1

Related Questions