0

I want to have some jQuery within my custom module to detect whenever a navbar item is clicked on the website. Is there any way of detecting jQuery events? Any help appreciated.

0

Yes, this will satisfy your requirement. Usually navigation menu will render in all the pages, so you have to

create a default.xml in your module vendor/module/frontend/layout/default.xml on you custom module and add the below code.

<?xml version="1.0" encoding="UTF-8"?>                                    
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1columns"  xsi:noNamespaceSchemaLocation="../../../../../../../lib/internal/Magento/Framework/View/Layout/etc/page_configuration.xsd">                       
<referenceContainer name="content">
    <block class="Magento\Framework\View\Element\Template"  name="ribbon_promo" template="vendor_module::customjs.phtml" before='-'>
    </block>
</referenceContainer>                                                   

In this code customjs.phtml will have your js which will render in all the pages.

create customjs.phtml in your module vendor/module/view/frontend/templates/customjs.phtml and the below code.

<script>
require(['jquery'],function($) {
    $(document).ready(function() {
        $(".navigation li").click(function(){
            alert("The navigation li is clicked.");
        });
    });
});</script>

This is working in a luma theme.

Hope this will help you. If you need any further information, please do let me know. peace :)

  • If you find this is useful give a credit. – G Prathap Feb 12 at 13:07
  • So, I have created both default.xml and customjs.phtml although it doesn't appear to be working. I have changed the template="" within default.xml to MyVendorName_MyModuleName::customjs.phtml is this correct? Or are there other things I need to change? – A. Fletcher Feb 12 at 13:30
  • Just to clarify, default.xml definitely goes within vendor/module/view/frontend/layout right? – A. Fletcher Feb 12 at 14:05
  • Updated the question and do what have explained here. Thanks – G Prathap Feb 13 at 4:56
  • If you find this is useful, just accept the answer. So others will use it – G Prathap Feb 19 at 9:00

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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