Search code examples
javascriptjqueryfade

Fading in menu items on load (with delay)


I was wondering how to make the individual menu items fade in with delay on page load.

I would like them to fade in not in a chronological order, so let's say first to appear would be #item 3, then #item 1, then #item 5 and so on...

How would such a jQuery or JavaScript code look and where in the code would I need to paste it?

Thanks a lot for help!


Solution

  • This should do the job. Basically give the elements that you want to fadeIn a class of hidden, or any other class name that you can target. You then set the display of that class to "none". Using jQuery you target each item that you want to fadeIn by its ID and you set a desired delay() before that item will be fadedIn using the fadeIn() function.

    So in this example #item2 will fadeIn after 1500ms, #item3 after 2500ms and #item1 after 4000ms.

    Hope this helps!

        <!doctype html>
        <html lang="en">
        
        <head>
            <meta charset="UTF-8">
            <title>Fade In</title>
        
            <style type="text/css">
                .hidden {
                    display: none;
                }
            </style>
        
        </head>
        
        <body>
            <nav>
                <ul>
                    <li id="item1" class="hidden">First</li>
                    <li id="item2" class="hidden">Second</li>
                    <li id="item3" class="hidden">Third</li>
                </ul>
            </nav>
            <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
            <script>
                $(document).ready(function() {
                    $('#item1').delay(4000).fadeIn('slow')
                    $('#item3').delay(2500).fadeIn('slow')
                    $('#item2').delay(1500).fadeIn('slow')
                })
            </script>
        </body>
        
        </html>