Magento – Add custom js to product view

magento2requirejs

I want to create the view more's button. I have:

app/design/frontend/{Name}/{theme}/Magento_Catalog/layout/catalog_product_view.xml

<referenceContainer name="product.info.main">
...
<block class="Magento\Framework\View\Element\Template" name="description.more.js" as="description" template="product/js.phtml"/>
...

app/design/frontend/{Name}/{theme}/requirejs-config.js

var config = {
    map: {
        '*' : {
            'descriptioncontent' : 'js/descriptioncontent',
        }
    }
};

app/design/frontend/{Name}/{theme}/web/js/descriptioncontent.js

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

app/design/frontend/{Name}/{theme}/Magento_Catalog/templates/product/js.phtml

<script>
// <![CDATA[
    require([
        'jquery',
        'description'
    ], function ($) {
        $(function () { // to ensure that code evaluates on page load
            alert('Check js.phtml');
            $('.product-info-main').ContentManagement();
        });
    });
// ]]>
</script>

For the moment i only have "alerts" to know if the files are correct, but i don't see nothing

Best Answer

In your template file, try to replace module name description with descriptioncontent.

app/design/frontend/{Name}/{theme}/Magento_Catalog/templates/product/js.phtml

<script>
// <![CDATA[
    require([
        'jquery',
        'descriptioncontent'
    ], function ($) {
        $(function () { // to ensure that code evaluates on page load
            alert('Check js.phtml');
            $('.product-info-main').ContentManagement();
        });
    });
// ]]>
</script>
Related Topic