Laravel proper procedure for using javascript.












2















I'm trying to properly use js inside of laravel. From what I understand all js gets concatenated into one app.js file inside public after running "npm run dev."



This is how I have set things up so far:
In resources/js I have created a custom.js file where I put all my custom js functions:



function myFunction() {
console.log("clicked fff");
}

$(document).ready(function(){
$(".www").click(function(){
$(".qqq").hide();
});
});


I have also required this in resources/js/app.js:



/**
* First we will load all of this project's JavaScript dependencies which
* includes Vue and other libraries. It is a great starting point when
* building robust, powerful web applications using Vue and Laravel.
*/

require('./bootstrap');
require('./custom');
window.Jquery = require('jquery');
window.Vue = require('vue');

/**
* The following block of code may be used to automatically register your
* Vue components. It will recursively scan this directory for the Vue
* components and automatically register them with their "basename".
*
* Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
*/

Vue.component('example-component', require('./components/ExampleComponent.vue'));

// const files = require.context('./', true, /.vue$/i)

// files.keys().map(key => {
// return Vue.component(_.last(key.split('/')).split('.')[0], files(key))
// })

/**
* Next, we will create a fresh Vue application instance and attach it to
* the page. Then, you may begin adding components to this application
* or customize the JavaScript scaffolding to fit your unique needs.
*/

const app = new Vue({
el: '#app'
});


Then my master layout looks like this:



    <!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<meta name="csrf-token" content="{{ csrf_token() }}">
<title>Website Name</title>
<link rel="stylesheet" href="{{ asset('css/app.css') }}">
<script src="{{ asset('js/app.js') }}"></script>
</head>
<body>
@include('inc.navbar')
<p class="qqq">jgkfjkj</p>
<button class="www">Click me to hide paragraphs</button>
<button onclick="myFunction()">Click me</button>
<!--More stuff below-->


Finally, I ran "npm run dev."
The jQuery stuff runs fine but the myFunction() does not. I get the following error:




Uncaught ReferenceError: myFunction is not defined
at HTMLButtonElement.onclick




What am I doing wrong?










share|improve this question



























    2















    I'm trying to properly use js inside of laravel. From what I understand all js gets concatenated into one app.js file inside public after running "npm run dev."



    This is how I have set things up so far:
    In resources/js I have created a custom.js file where I put all my custom js functions:



    function myFunction() {
    console.log("clicked fff");
    }

    $(document).ready(function(){
    $(".www").click(function(){
    $(".qqq").hide();
    });
    });


    I have also required this in resources/js/app.js:



    /**
    * First we will load all of this project's JavaScript dependencies which
    * includes Vue and other libraries. It is a great starting point when
    * building robust, powerful web applications using Vue and Laravel.
    */

    require('./bootstrap');
    require('./custom');
    window.Jquery = require('jquery');
    window.Vue = require('vue');

    /**
    * The following block of code may be used to automatically register your
    * Vue components. It will recursively scan this directory for the Vue
    * components and automatically register them with their "basename".
    *
    * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
    */

    Vue.component('example-component', require('./components/ExampleComponent.vue'));

    // const files = require.context('./', true, /.vue$/i)

    // files.keys().map(key => {
    // return Vue.component(_.last(key.split('/')).split('.')[0], files(key))
    // })

    /**
    * Next, we will create a fresh Vue application instance and attach it to
    * the page. Then, you may begin adding components to this application
    * or customize the JavaScript scaffolding to fit your unique needs.
    */

    const app = new Vue({
    el: '#app'
    });


    Then my master layout looks like this:



        <!DOCTYPE html>
    <html lang="en" dir="ltr">
    <head>
    <meta charset="utf-8">
    <meta name="csrf-token" content="{{ csrf_token() }}">
    <title>Website Name</title>
    <link rel="stylesheet" href="{{ asset('css/app.css') }}">
    <script src="{{ asset('js/app.js') }}"></script>
    </head>
    <body>
    @include('inc.navbar')
    <p class="qqq">jgkfjkj</p>
    <button class="www">Click me to hide paragraphs</button>
    <button onclick="myFunction()">Click me</button>
    <!--More stuff below-->


    Finally, I ran "npm run dev."
    The jQuery stuff runs fine but the myFunction() does not. I get the following error:




    Uncaught ReferenceError: myFunction is not defined
    at HTMLButtonElement.onclick




    What am I doing wrong?










    share|improve this question

























      2












      2








      2








      I'm trying to properly use js inside of laravel. From what I understand all js gets concatenated into one app.js file inside public after running "npm run dev."



      This is how I have set things up so far:
      In resources/js I have created a custom.js file where I put all my custom js functions:



      function myFunction() {
      console.log("clicked fff");
      }

      $(document).ready(function(){
      $(".www").click(function(){
      $(".qqq").hide();
      });
      });


      I have also required this in resources/js/app.js:



      /**
      * First we will load all of this project's JavaScript dependencies which
      * includes Vue and other libraries. It is a great starting point when
      * building robust, powerful web applications using Vue and Laravel.
      */

      require('./bootstrap');
      require('./custom');
      window.Jquery = require('jquery');
      window.Vue = require('vue');

      /**
      * The following block of code may be used to automatically register your
      * Vue components. It will recursively scan this directory for the Vue
      * components and automatically register them with their "basename".
      *
      * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
      */

      Vue.component('example-component', require('./components/ExampleComponent.vue'));

      // const files = require.context('./', true, /.vue$/i)

      // files.keys().map(key => {
      // return Vue.component(_.last(key.split('/')).split('.')[0], files(key))
      // })

      /**
      * Next, we will create a fresh Vue application instance and attach it to
      * the page. Then, you may begin adding components to this application
      * or customize the JavaScript scaffolding to fit your unique needs.
      */

      const app = new Vue({
      el: '#app'
      });


      Then my master layout looks like this:



          <!DOCTYPE html>
      <html lang="en" dir="ltr">
      <head>
      <meta charset="utf-8">
      <meta name="csrf-token" content="{{ csrf_token() }}">
      <title>Website Name</title>
      <link rel="stylesheet" href="{{ asset('css/app.css') }}">
      <script src="{{ asset('js/app.js') }}"></script>
      </head>
      <body>
      @include('inc.navbar')
      <p class="qqq">jgkfjkj</p>
      <button class="www">Click me to hide paragraphs</button>
      <button onclick="myFunction()">Click me</button>
      <!--More stuff below-->


      Finally, I ran "npm run dev."
      The jQuery stuff runs fine but the myFunction() does not. I get the following error:




      Uncaught ReferenceError: myFunction is not defined
      at HTMLButtonElement.onclick




      What am I doing wrong?










      share|improve this question














      I'm trying to properly use js inside of laravel. From what I understand all js gets concatenated into one app.js file inside public after running "npm run dev."



      This is how I have set things up so far:
      In resources/js I have created a custom.js file where I put all my custom js functions:



      function myFunction() {
      console.log("clicked fff");
      }

      $(document).ready(function(){
      $(".www").click(function(){
      $(".qqq").hide();
      });
      });


      I have also required this in resources/js/app.js:



      /**
      * First we will load all of this project's JavaScript dependencies which
      * includes Vue and other libraries. It is a great starting point when
      * building robust, powerful web applications using Vue and Laravel.
      */

      require('./bootstrap');
      require('./custom');
      window.Jquery = require('jquery');
      window.Vue = require('vue');

      /**
      * The following block of code may be used to automatically register your
      * Vue components. It will recursively scan this directory for the Vue
      * components and automatically register them with their "basename".
      *
      * Eg. ./components/ExampleComponent.vue -> <example-component></example-component>
      */

      Vue.component('example-component', require('./components/ExampleComponent.vue'));

      // const files = require.context('./', true, /.vue$/i)

      // files.keys().map(key => {
      // return Vue.component(_.last(key.split('/')).split('.')[0], files(key))
      // })

      /**
      * Next, we will create a fresh Vue application instance and attach it to
      * the page. Then, you may begin adding components to this application
      * or customize the JavaScript scaffolding to fit your unique needs.
      */

      const app = new Vue({
      el: '#app'
      });


      Then my master layout looks like this:



          <!DOCTYPE html>
      <html lang="en" dir="ltr">
      <head>
      <meta charset="utf-8">
      <meta name="csrf-token" content="{{ csrf_token() }}">
      <title>Website Name</title>
      <link rel="stylesheet" href="{{ asset('css/app.css') }}">
      <script src="{{ asset('js/app.js') }}"></script>
      </head>
      <body>
      @include('inc.navbar')
      <p class="qqq">jgkfjkj</p>
      <button class="www">Click me to hide paragraphs</button>
      <button onclick="myFunction()">Click me</button>
      <!--More stuff below-->


      Finally, I ran "npm run dev."
      The jQuery stuff runs fine but the myFunction() does not. I get the following error:




      Uncaught ReferenceError: myFunction is not defined
      at HTMLButtonElement.onclick




      What am I doing wrong?







      javascript node.js laravel






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 22 '18 at 23:43









      AkashAkash

      245




      245
























          1 Answer
          1






          active

          oldest

          votes


















          0














          why this doesn't work



          All your js code gets bundled in one big js file. To prevent naming collision woth other js code its wrapped in a function.



          So when you define a function (like myFunction) it's only available in that the function that the bundler wraps it in. (This is through the nature of javascripts function scope)



          solutions



          One way to fix this problem is to explicitly assign it to the global scope (which is the window object).



          window.myFunction = function() { alert('quick and dirty') }


          A more programmatic way is to add an eventListener to the onClick event and then call your function, like so:



          document.getElementById('yourButtonId').addEventListener('click', myFunction)





          share|improve this answer

























            Your Answer






            StackExchange.ifUsing("editor", function () {
            StackExchange.using("externalEditor", function () {
            StackExchange.using("snippets", function () {
            StackExchange.snippets.init();
            });
            });
            }, "code-snippets");

            StackExchange.ready(function() {
            var channelOptions = {
            tags: "".split(" "),
            id: "1"
            };
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function() {
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled) {
            StackExchange.using("snippets", function() {
            createEditor();
            });
            }
            else {
            createEditor();
            }
            });

            function createEditor() {
            StackExchange.prepareEditor({
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader: {
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            },
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            });


            }
            });














            draft saved

            draft discarded


















            StackExchange.ready(
            function () {
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439149%2flaravel-proper-procedure-for-using-javascript%23new-answer', 'question_page');
            }
            );

            Post as a guest















            Required, but never shown

























            1 Answer
            1






            active

            oldest

            votes








            1 Answer
            1






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            why this doesn't work



            All your js code gets bundled in one big js file. To prevent naming collision woth other js code its wrapped in a function.



            So when you define a function (like myFunction) it's only available in that the function that the bundler wraps it in. (This is through the nature of javascripts function scope)



            solutions



            One way to fix this problem is to explicitly assign it to the global scope (which is the window object).



            window.myFunction = function() { alert('quick and dirty') }


            A more programmatic way is to add an eventListener to the onClick event and then call your function, like so:



            document.getElementById('yourButtonId').addEventListener('click', myFunction)





            share|improve this answer






























              0














              why this doesn't work



              All your js code gets bundled in one big js file. To prevent naming collision woth other js code its wrapped in a function.



              So when you define a function (like myFunction) it's only available in that the function that the bundler wraps it in. (This is through the nature of javascripts function scope)



              solutions



              One way to fix this problem is to explicitly assign it to the global scope (which is the window object).



              window.myFunction = function() { alert('quick and dirty') }


              A more programmatic way is to add an eventListener to the onClick event and then call your function, like so:



              document.getElementById('yourButtonId').addEventListener('click', myFunction)





              share|improve this answer




























                0












                0








                0







                why this doesn't work



                All your js code gets bundled in one big js file. To prevent naming collision woth other js code its wrapped in a function.



                So when you define a function (like myFunction) it's only available in that the function that the bundler wraps it in. (This is through the nature of javascripts function scope)



                solutions



                One way to fix this problem is to explicitly assign it to the global scope (which is the window object).



                window.myFunction = function() { alert('quick and dirty') }


                A more programmatic way is to add an eventListener to the onClick event and then call your function, like so:



                document.getElementById('yourButtonId').addEventListener('click', myFunction)





                share|improve this answer















                why this doesn't work



                All your js code gets bundled in one big js file. To prevent naming collision woth other js code its wrapped in a function.



                So when you define a function (like myFunction) it's only available in that the function that the bundler wraps it in. (This is through the nature of javascripts function scope)



                solutions



                One way to fix this problem is to explicitly assign it to the global scope (which is the window object).



                window.myFunction = function() { alert('quick and dirty') }


                A more programmatic way is to add an eventListener to the onClick event and then call your function, like so:



                document.getElementById('yourButtonId').addEventListener('click', myFunction)






                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Nov 23 '18 at 0:00

























                answered Nov 22 '18 at 23:55









                Y. GherbiY. Gherbi

                25728




                25728
































                    draft saved

                    draft discarded




















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid



                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.


                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function () {
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53439149%2flaravel-proper-procedure-for-using-javascript%23new-answer', 'question_page');
                    }
                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    這個網誌中的熱門文章

                    Xamarin.form Move up view when keyboard appear

                    Post-Redirect-Get with Spring WebFlux and Thymeleaf

                    Anylogic : not able to use stopDelay()