2

I try to add custom java-script file but giving error of different kind, please give me a proper example of adding JS in Magento 2 module and use it in phtml.

2

Create requirejs-config.js under app/code/[Vendor]/[Module]/view/frontend and the below code:

var config = {
    map: {
        '*': {
            custom: 'Vendor_Module/js/custom',
        }
    }
};

This will add custom.js no need to add .js extension. Now add your custom.js to the below directory

app/code/[Vendor]/[Module]/view/frontend/web/js/custom.js

Now you can use your js function on phtml by using below code:

 <script>
    (function  () {
        require(["jquery","custom"],function($) {
            $(document).ready(function() {
                // Your code
            });
        });
    })();
</script>

Hope this helps!

| improve this answer | |
  • actually i add this but how to use in phtml file like alert pop up – M RIZWAN May 29 '18 at 8:43
  • I have shared you the phtml code as well. You can add alert under $(document).ready. – Sukumar Gorai May 29 '18 at 8:44
  • i follow this but getting error in console in static file this is not found: custom.js not found in static files folder 404 – M RIZWAN May 30 '18 at 5:32
  • and also /magento2/pub/static/version1527655585/frontend/Magento/luma/en_US/custom.js:1 Failed to load resource: the server responded with a status of 404 (Not Found) – M RIZWAN May 30 '18 at 5:33
  • Did you add the Js under web directory? – Sukumar Gorai May 30 '18 at 5:41
0

Create new custom.js file under :

/app/design/frontend/Vendor/YourTheme/web/js/custom.js

require([
'jquery',
'owl.carousel'
], function($){
    $(document).ready(function() {
         // Your Custom Code here
    });
});

Create New requirejs-config.js under your theme

/app/code/Vendor/Module/view/frontend/requirejs-config.js

var config = {
    map: {
        '*' : {
            'owl.carousel' : 'Vendor_Module/js/owl.carousel'
        }
    },
    deps: [
        "jquery",
        "custom"
    ]
};

In PHTML file :

<script>
   require([
       'jquery',
       'owl.carousel'
       ], function($){
           $(document).ready(function() {
                // Your Custom Code here
           });
       });
</script>
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.