Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Magento2 gallery afterLoad callback

I need to move the product gallery navigation thumbnails on horizontal position if the screen is less than 768px wide.

For this I need to hook up on a callback that is triggered after the gallery is completely loaded.

How to do this when the gallery widget is initialized via the x-magento-init method:

<script type="text/x-magento-init">
    {
        "[data-gallery-role=gallery-placeholder]": {
            "mage/gallery/gallery": {
                ...

            }
        }
    }
</script>

I tried adding:

<script type="text/javascript">
    require(['jquery', 'mage/gallery/gallery'], function($, gallery){
        console.log($('[data-gallery-role=gallery-placeholder]').data('gallery'));
    });
</script>

And it outputs undefined. But when I call the same thing from the console (after the gallery was loaded) it contains the gallery object where I can call the fotorama API methods.

So how can I get the .data('gallery') object after the gallery is initialized ?

Many thanks!

like image 905
Serbu Florin-Adrian Avatar asked Jul 06 '16 09:07

Serbu Florin-Adrian


1 Answers

I found the solution by using the gallery:loaded event that is triggered after the fotorama api object is added.

<script type="text/javascript">
    require(['jquery', 'mage/gallery/gallery'], function($, gallery){
        $('[data-gallery-role=gallery-placeholder]').on('gallery:loaded', function () {
            if($(window).width() < 768){
                $(this).on('fotorama:ready', function(){
                    var  api = $(this).data('gallery');
                    if(api.fotorama.options.navdir == 'vertical'){
                        api.fotorama.options.navdir = 'horizontal';
                        api.fotorama.resize();
                    }
                });
            }
        });
    });
</script>

Updating options with api.updateOptions() on gallery:loaded event does nothing because the options are reset after that step. So I had to hook to fotorama:ready event.

like image 115
Serbu Florin-Adrian Avatar answered Oct 20 '22 01:10

Serbu Florin-Adrian