6

I'm trying to get a custom js on the product page, I'm using Magento 2, what's the page I need to edit to do that? I've already tried to create a local.xml into /app/design/frontend/Venustheme/yume/Magento_Catalog/layout , and add the code inside , but it doesn't work..

1 Answer 1

15

For example, We have our folder structure of current theme:

enter image description here

We should focus four files:

Magento_Catalog/layout/catalog_product_view.xml Magento_Catalog/templates/product/js.phtml

  • Add new template to call our jQuery plugin. That helps us to include our js on product detail page only.

Layout

#app/design/frontend/Boolfly/yume/Magento_Catalog/layout/catalog_product_view.xml

<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <referenceContainer name="content">
        <block class="Magento\Framework\View\Element\Template"
               name="custom.js" as="custom.js" template="Magento_Catalog::product/js.phtml"/>
    </referenceContainer>
</page>

Template:

#app/design/frontend/Boolfly/yume/Magento_Catalog/templates/product/js.phtml

    <script>// <![CDATA[
        require([
            'jquery',
            'hello'
        ], function ($) {
            $('.product-info-main').HelloWorld();
        });
        // ]]>
    </script>

app/design/frontend/Boolfly/yume/web/js/custom.js

  • We can create our own custom jQuery plugin.

    define('jquery', function($) {
    
        $.fn.HelloWorld = function() {
            alert('Here');
        }
    
        }(jQuery)
    );
    

app/design/frontend/Boolfly/yume/requirejs-config.js

  • Create a RequireJS configuration file.

    var config = {
        map: {
            '*' : {
                'hello' : 'js/custom'
            }
        }
    };
    

Clear Magento Cache and run static content deploy:

php bin/magento setup:static-content:deploy
php bin/magento cache:clean

We can read more here how to create custom Javascript: http://devdocs.magento.com/guides/v2.0/javascript-dev-guide/javascript/custom_js.html

4
  • thank you for your time @Khoa TruongDinh , that worked fine , what about if I need to insert a js library only on the home page ?
    – alexcr
    Commented May 12, 2016 at 12:20
  • You can see here:boolfly.com/magento-2-slider-with-owl-carousel. We can add Require js in cms home page. Commented May 12, 2016 at 16:17
  • @KhoaTruongDinh the above link has expired can u give any other reference thank u...
    – 3bu1
    Commented May 16, 2017 at 19:18
  • @KhoaTruongDinh can we use custom.js and requirejs-config in the module Magento_Catalog ? Commented Dec 28, 2021 at 18:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.