If you need Custom JavaScript In Magento2 then you can follow this blog step by step.
Step 1: Create registration.php file.
app/code/Bluethink/CustomJS/registration.php
1 2 3 4 5 6 |
<?php \Magento\Framework\Component\ComponentRegistrar::register( \Magento\Framework\Component\ComponentRegistrar::MODULE, 'Bluethink_CustomJS', __DIR__ ); |
Step 2: Create module.xml file.
app/code/Bluethink/CustomJS/etc/module.xml
1 2 3 4 5 |
<?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="Bluethink_CustomJS" setup_version="1.0.0"> </module> </config> |
Step 3: Create requirejs-config.js file.
app/code/Bluethink/CustomJS/view/frontend/requirejs-config.js
1 2 3 4 5 6 7 |
var config = { map: { '*': { wktestrequire: 'Bluethink_CustomJS/js/wkrequirejs', } } }; |
Step 4: Create test.phtml file.
app/code/Bluethink/CustomJS/view/frontend/templates/test.phtml
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
<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: Creat wkrequirejs.js file.
app/code/Bluethink/CustomJS/view/frontend/web/js/wkrequirejs.js
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
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
bluethinkinc_blog
2022-09-30