3

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..

8

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

  • 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 May 12 '16 at 12:20
  • You can see here:boolfly.com/magento-2-slider-with-owl-carousel. We can add Require js in cms home page. – Khoa TruongDinh May 12 '16 at 16:17
  • @KhoaTruongDinh the above link has expired can u give any other reference thank u... – 3bu1 May 16 '17 at 19:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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