I need to use require js to use jquery in my block. Do I have to declare for each function require JS at each beginning or there is a way to declare it only once?

here is my code, thanks

my html

<div class="mainMenu">
    <div style="background-color: black;color: white;">
        <div onClick="openCategory(1)">MENU 1</div>
        <div onClick="openCategory(2)">MENU 2</div>
        <div onClick="openCategory(3)">MENU 3</div>
<div onClick="openMainMenu()">

SCRIPT inside phtml

    let menu
    require(['jquery', 'jquery/ui'], function($){
            url: "https://catfact.ninja/fact",
            context: document.body
        }).done(function(value) {
            menu = []
            menu.forEach(element => {
                $('.mainMenu').append("<div class='menuContainer menuNumber" + element.id + "'>" + element.name + "</div>")

    function openMainMenu(){
        require(['jquery', 'jquery/ui'], function($){
    function openCategory(categoryNumber){
        require(['jquery', 'jquery/ui'], function($){
            console.log($('.menuNumber' + categoryNumber).css("visibility", "visible"));

1 Answer 1


no this is a not a good approach to use JS code logic in the PHTML file , since magento is all about extensibility for developers like us , you can try moving the JS files to the separate directory view/frontend/web/js by using either jquery widget or component etc by follow this link you may have an idea - https://developer.adobe.com/commerce/frontend-core/javascript/custom/

This way if any other developers wants to over-ride that JS file they can do so easily by using mixins or map etc.

Please do let me know if this answer fulfils your question or do you need the entire code to move this custom JS logic to a separate JS file or not, and do like as such motivates me to post more answers.

  • thanks, I modified the code yesterday to create a separate js file with js folder and requirejs-config.js but my question was about the declaration of require('jquery'), can I used multiple time like that in a single file ? Commented Sep 16, 2022 at 12:18
  • Yes @kevinrichard you can in separate script tags in that same PHTML file. Commented Sep 16, 2022 at 13:07
  • ok , you can create a new answer with this information, that I will confiirm, or edit this answer Commented Sep 18, 2022 at 6:33
  • Hi @kevinrichard Can i know for what purpose are you asking the whole answer ? Do you mean the full JS file and why because you have already achieved it right ? Commented Sep 18, 2022 at 18:33

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.