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.

SR/Js/view/frontend/web/js/srjs.js
define([
    "jquery",
    "jquery/ui"
], 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

SR/Js/view/frontend/templates/js.phtml
<div>
    <p id="elem">Click Me!</p>
</div>
<script type="text/x-magento-init">
{
    "#elem": { "SR_Js/js/srjs": {} }
}
</script>

That’s it!

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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