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>
</div>
<div onClick="openMainMenu()">
OUVRIR MENU
</div>
SCRIPT inside phtml
<script>
let menu
require(['jquery', 'jquery/ui'], function($){
$.ajax({
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($){
$('.mainMenu').show()
});
}
function openCategory(categoryNumber){
require(['jquery', 'jquery/ui'], function($){
console.log($('.menuNumber' + categoryNumber).css("visibility", "visible"));
});
}
</script>
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 ?kevin richard– kevin richard2022年09月16日 12:18:00 +00:00Commented Sep 16, 2022 at 12:18
-
Yes @kevinrichard you can in separate script tags in that same PHTML file.Bharath Kumar– Bharath Kumar2022年09月16日 13:07:30 +00:00Commented Sep 16, 2022 at 13:07
-
ok , you can create a new answer with this information, that I will confiirm, or edit this answerkevin richard– kevin richard2022年09月18日 06:33:32 +00:00Commented 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 ?Bharath Kumar– Bharath Kumar2022年09月18日 18:33:38 +00:00Commented Sep 18, 2022 at 18:33