I'm having the problem currently where I need to run some jQuery on my Minicart. However, I can't select anything from the Minicart because the jQuery is executing before the Minicart is actually loaded on to the page.
My jQuery is contained within:
Magento_Checkout/templates/cart/minicart.phtml
and the jQuery is as follows:
<script>
require(["jquery"], function ($) {
//jQuery(document).ready(function(){
jQuery(window).on('load', function(){
let counter = 0;
$("#minicart-content-wrapper").children().each(function(){
counter++;
});
console.log("Num items in minicart: " + counter);
});
});
</script>
You can see from this I have tried both document ready and window on load but both return 0 in the counter. I have managed to select the parent of the Minicart and that outputs 1 so the jQuery is working as intended.
So my question is, is there an alternative place I can run some jQuery so that it will execute once the Minicart has finished loading on the page?
Update:
I have figured out a short-term solution where I can execute some jQuery once the Minicart logo is clicked however, this is not ideal as I want to edit the styling of the Minicart. This styling should be done straight away rather than when a user clicks the logo because on slower devices this could affect the look and feel as elements change on the page.
3 Answers 3
You can use the contentUpdated event like this :
<script type="text/javascript">
require(['jquery', 'domReady!'], function($) {
$('[data-block="minicart"]').on('contentUpdated', function () {
console.log('minicart updated');
// Do what you need here.
}
});
</script>
-
1THANKYOU. I'm trying to execute some js on the knockout. You would not believe how long I've been trying to get something like this working. Tried afterRenders, Extending components, modifying the customer cart model. You name it, it just didn't work. This though, this was super simple. THANKS :D :DThomas Harding– Thomas Harding2024年03月12日 21:51:32 +00:00Commented Mar 12, 2024 at 21:51
Since you defined the dollar sign in the function, you should use it also in the document ready event.
<script>
require(["jquery"], function ($) {
$(document).ready(function(){
let counter = 0;
$("#minicart-content-wrapper").children().each(function(){
counter++;
});
console.log("Num items in minicart: " + counter);
});
});
</script>
Try this.
<script type="text/javascript">
require(['jquery'], function($) {
$(function(){
try{
var mage = localStorage.getItem('mage-cache-storage');
mage = $.parseJSON(mage);
console.log("Num items in minicart: " + mage.cart.items.length);
}
catch(e)
{
console.log('need to reload customer section');
}
$(document).on('customer-data-reload', function (event, sectionNames) {
if(sectionNames.indexOf('cart') != -1)
{
setTimeout(function() {
var counter = $("#minicart-content-wrapper ol#mini-cart > li").length;
console.log("Num items in minicart: " + counter);
}, 1000);
}
});
});
});
</script>
$(document).ready(function()