How to add custom javascript in Magento 2 with requireJS?

How To Add Custom Javascript In Magento 2 With RequireJS

Create a new module with Bay20_Bay20CustomJS

Step 1: Create registration.php file.

app/code/Bay20/Bay20CustomJS/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
	\Magento\Framework\Component\ComponentRegistrar::MODULE,
	'Bay20_Bay20CustomJS',
	__DIR__
);

Step 2: Create module.xml file.

app/code/Bay20/Bay20CustomJS/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Bay20_Bay20CustomJS" setup_version="1.0.0">
    </module>
</config>

Step 3: Create requirejs-config.js file.

app/code/Bay20/Bay20CustomJS/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            wktestrequire: 'Bay20_Bay20CustomJS/js/wkrequirejs',
        }
    }
};

Step 4: Create test.phtml file

app/code/Bay20/Bay20CustomJS/view/frontend/templates/test.phtml

<div id="testdiv">
	<a>Test anchor tag</a>
</div>

<?php
$formData = [
    'divElement'       =>  '#testdiv',
];
$serializedFormData = $this->helper('Magento\Framework\Json\Helper\Data')->jsonEncode($formData);
?>
<script type="text/x-magento-init">
    {
        "*": {
            "wktestrequire": <?php /* @noEscape */ echo $serializedFormData; ?>
        }
    }
</script>

Step 5: Create wkrequirejs.js file.

app/code/Bay20/Bay20CustomJS/view/frontend/web/js/wkrequirejs.js

define([
    "jquery",
    'Magento_Ui/js/modal/alert',
    "jquery/ui",
], function ($, alert) {
    'use strict';
    $.widget('mage.wktestrequire', {
        options: {
            confirmMsg: ('divElement is removed.')
        },
        _create: function () {
            var self = this;
            $(self.options.divElement).remove();
            alert({
                content: self.options.confirmMsg
            });
        }
    });
    return $.mage.wktestrequire;
});

Step 6: Run the below command.

php bin/magento setup:upgrade

Please contact us at manish@bay20.com or call us at +91-8800519180 for any support related to Magento 2. You can also visit the Magento2 development page to check the services we offer.