cancel
Showing results for 
Search instead for 
Did you mean: 

javascript to external js in magento2

javascript to external js in magento2

I am having javascript code in my phtml file, but I want to do it from layout and create separate phtml file pass variable from require js. Can anyone tell me how to do this?

My phtml file code is

    <script>    document.getElementById("hello").style.display = "none";
    function hideItem(){
    const pattern = /^\b[A-Z0-9._%-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\b$/i
    const textValue = document.getElementById("names").value;
    if(!pattern.test(textValue)){
        document.getElementById("hello").style.display = "none";
    }
    else{
        document.getElementById("hello").style.display = "block";
     }
}
document.getElementById("msgbutton").addEventListener("click", hideItem);
function validateItem() {
var response = val.getResponse();
if(response.length == 0) {
      document.getElementById('test-error').innerHTML = '<span style="color:red;"><?= __('This field is required') ?></span>';
    return false;
}
return true;
}

 function test() {
document.getElementById('test-error').innerHTML = '';
 }
2 REPLIES 2

Re: javascript to external js in magento2

Today I will explain in this article, that how you can create a configurable JS external URL and then map it with another js in magento 2.

Re: javascript to external js in magento2

@aryanakhtaab63 

Please use the below code in the JS file:
app/code/Vendor/Module/view/frontend/web/js/test.js
<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <script src="Vendor_Module::js/test.js"/>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Mageplaza\HelloWorld\Block\Display" name="helloworld_display" template="Vendor_Module::my.phtml" />
        </referenceContainer>
    </body>
</page>

var config = {
    map: {
        '*': {
            'myscript': 'Vendor_Module/js/productdesigner'
        }
    }
};
Problem solved? Click Kudos and "Accept as Solution".
200+ Magento 2 Extensions for Enhanced Shopping Experience.