How to add custom javascript in magento 2

Magento 2 ship with most popular javascript library like Jquery, requireJS, KnockoutJS. Today I discuss, how you can create a custom javascript and load using requireJS. So lets start…

If you miss my previous post Click Here

Create a custom js file following location.

], function($) {
    "use strict";

    //creating jquery widget
    $.widget('mage.srjs', {
        _create: function() {
            console.log('hey, srjs is loaded!')
            //bind click event of elem id
            this.element.on('click', function(e){
                console.log('Click ME!')


    return $.mage.srjs;

Create a phtml file. location

    <p id="elem">Click Me!</p>
<script type="text/x-magento-init">
    "#elem": { "SR_Js/js/srjs": {} }

That’s it!

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s