Juan David
Juan David

Reputation: 247

Load script javascript

I'm using 3 html, 1 with the header, 1 with footer, and another with the base of everything. I am loading the header and footer with the following code

jQuery(document).ready(function ($) {
    $('#header-load').load('/app/templates/header.html', function () {
        console.log('header loaded')
    });
    $('#footer-load').load('/app/templates/footer.html', function () {
        console.log('footer loaded')
    });
    $('.dropdown').on('show.bs.dropdown', function (e) {
        $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
    });

    $('.dropdown').on('hide.bs.dropdown', function (e) {
        $(this).find('.dropdown-menu').first().stop(true, true).slideUp(200);
    });

})

In the base html, this is the following

<!DOCTYPE html>
<html class="no-focus" lang="en">
<head>
    <meta charset="utf-8">
    <title>Home</title>
    <link rel="stylesheet" id="css-main" href="/public/css/app.css">
    <!-- END Stylesheets -->
</head>
<body>
    <!-- Page Container -->
    <div id="page-container" class="">
        <!-- Header -->
        <div id="header-load"></div>
        <!-- END Header -->

        <!-- Main Container -->
        <main id="main-container">


        </main>
        <!-- END Main Container -->

        <!-- Footer -->
        <div id="footer-load"></div>
        <!-- END Footer -->
    </div>
    <!-- END Page Container -->

    <!-- JS-->
    <script src="/public/library/jquery/dist/jquery.min.js"></script>
    <script src="/public/library/bootstrap/dist/js/bootstrap.min.js"></script>
    <script src="/public/js/app.js"></script>
</body>

</html>

I have a function in app.js to load into the header.html, but it does not work..

Load the header and footer but the other function does not

Upvotes: 0

Views: 268

Answers (1)

Erdogan Oksuz
Erdogan Oksuz

Reputation: 621

.load work async like ajax, you must wait for request complete then find elements and define events.

jQuery(document).ready(function ($) {
$('#header-load').load('/app/templates/header.html', function () {
    console.log('header loaded')
    $('#footer-load').load('/app/templates/footer.html', function () {
        console.log('footer loaded')
        $('.dropdown').on('show.bs.dropdown', function (e) {
            $(this).find('.dropdown-menu').first().stop(true, true).slideDown(300);
        });

        $('.dropdown').on('hide.bs.dropdown', function (e) {
            $(this).find('.dropdown-menu').first().stop(true, true).slideUp(200);
        });
    });
})
});

Upvotes: 1

Related Questions