Back to Top

How to use javascript in magento2

Updated 20 February 2024

Here we learn how to use javascript in magento2

1# First we will create requirejs-config.js file in folder app/code/NameSpace/Module/view/frontend

/**
 * @author      Webkul Software Private Limited
 */


var config = {
    map: {
        '*': {
            customjs: 'NameSpace_ModuleName/js/customjsfile'
            // 'js/customjsfile' is path of javascript file in your module in web folder
            /* Here you can add multiple mapping 
             * of javascript file separated by comma ( , )*/
        }
    }
};

In case of add js file in admin section  you need to create this above file in app/code/NameSpace/Module/view/adminhtml folder

2# Now i’ll create javascript file which i want to use

create ‘customjsfile.js’ file in app/code/NameSpace/Module/view/frontend/web/js

/**
 * @author Webkul Software Private Limited
 */

define([
    "jquery",
    "jquery/ui"
], function($) {
    "use strict";
    $.widget('modulename.customname', {
        _create: function() {
            var yourData = this.options;
            /*this.options contaion all variables which you pass in it for
             use in your javascript code */
            console.log(this.options); 
            // here you can write your javascript code as your requirement
        }
    });
    return $.modulename.customname;
});

3# Now we’ll call this javascript file on phtml file.

add following code in our phtml file where we want to use javascript

<script type="text/x-magento-init">
    {
        "body" : {
             "customjs": // customjs name as we map in our requirejs-config.js file
                    {
                        /* variables which we want to use in our javascript code*/
                        "yourvar1": "<?php echo $yourvar1 ?>", 
                        "yourvar2" : "<?php echo $yourvar2 ?>"
                    }
        }
    }
</script>

after these steps flush cache and check your page where you add this javascript .

Thanks …

Searching for an experienced
Magento Company ?
Find out More
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home