How to add script on specific view file in laravel while extending layout

Updated at 05-Sep-2021, By samar

How to add script on specific view file in laravel while extending layout

Through the use of the programming language, we will work together to solve the "How to add script on specific view file in laravel while extending layout" puzzle in this lesson.

Sometimes we need to add a script on a specific view file which we can’t add to the layout file then we can use @stack and @push method to add script on specific view file in laravel while extending layout file.
  • Add fixed header script code to a specific view file using @stack and @push

    //resources\views\layouts\<app>.blade.php
    
    //Add before the closing of body tag 
    @stack('child-scripts')
    
    //resources\views\<home>.blade.php
    //Add at the bottom of child view file
    @push('child-scripts')
    @include('partials.js.header_fixed')
    @endpush
    //resources\views\partials\js\header_fixed.blade.php
    //Javascript code to fixed header
    <script>
    document.addEventListener("DOMContentLoaded", function(){
        window.addEventListener('scroll', function() {
            if (window.scrollY > 50) {
                document.getElementById('navbar_top').classList.add('fixed-top');
                // add padding top to show content behind navbar
                navbar_height = document.querySelector('.navbar').offsetHeight;
                document.body.style.paddingTop = navbar_height + 'px';
            } else {
                document.getElementById('navbar_top').classList.remove('fixed-top');
                // remove padding top from body
                document.body.style.paddingTop = '0';
            } 
        });
    }); 
    </script>
    

    This code snippet will help you to add a particular script code to a specific view file on which you want to add while extending the layout file in laravel. Sometimes we don’t need to add a script on all pages while extending a particular layout. This code snippet will work for you in case you don’t want to add a particular script on every page.

Back to code snippet queries related laravel