Skip to content

How to add JS with jQuery containing multiple functions to Magento 2.4.4

I am using Magento 2.4.4CE and I have successfully added a jquery based JS file to a CMS page’s header by using a cms_page_view_selectable_url_somename.xml file in my custom theme. I have the following line added in the head section to attach the JS file to the page:

<script src="Magento_Cms::js/somefunction.js"></script>

I know the file is being recognized by Magento as I am getting errors. The JS file that I added was working well on my Magento 1.7 cart with the same html elements that I added to M2.4.4. I am assuming there JS security implementations in M2.4 that are making this more difficult.

Any function call from the html elements on the page, such as onchange=”ReCal()” results in the following error:

Uncaught ReferenceError: ReCal is not defined

Also on page load I am getting the following error:

Uncaught ReferenceError: ReCal is not defined
at HTMLDivElement. (mathcalc.js:16:5)
at HTMLDivElement.dispatch (jquery.js:5430:49)
at elemData.handle (jquery.js:5234:47)

Here is the basic structure of the js file:

require(['jquery','jquery/ui'], function ($) {

    $(document).ready(function() {
        windowWidth = $( window ).width();
        $("#add-row").click(function () {
            
            //do something and it is working
        });
                            
        if(windowWidth > 767) {
            //do something and call another function
            ReCal();
            
        }
    });
    
    function ReCal() {
        //do some jquery based updates for input values on form
    }
});

I am a novice coder and I am trying to learn the proper way that Magento 2.3 onwards allows js execution. Any help or guidance would be greatly appreciated.