Magento – magento 2 fotorama lightbox on single image

fotoramamagento2

I need to add a lightbox functionality for zooming single images in blocks. I thought to use magento 2 fotorama lightbox that's used for the product gallery. I would show the block in the product page so the js library would be already loaded. Any advice or help? I don't know how to make it.
Thanks a lot.

Best Answer

Magento 2 offers a lot of jQuery Widgets out of the box. Magnifier Widget would solve your solution. High level implementation is as follows:

<script type="text/x-magento-init">
  "<element_selector>": {
    "mage/gallery/gallery": {
        "data": [{
            "thumb": "<small_image_url>",
            "img": "<small_image_url>",
            "full": "<small_image_url>",
            "caption": "<message>",
            "isMain": "<true/false>"
        }],
        "mixins": ["magnifier/magnify"],
        "magnifierOpts": {
           "enabled": <true/false>,
           "eventType": "<hover/click>",
           "width": <number>,
           "height": <number>,
           "top": <number>,
           "left": <number>,
           "fullscreenzoom": <number>
        }
    }
  }
</script>

You can use this code in any template file. Hope this helps.

EDIT : this method does not work due to its dependent on the fotorama gallery, here is a jQuery Fancybox alternative

file: app/code/design/frontend/Vendor/Package/Magento_Theme/layout/default.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<page layout="3columns" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="head.additional">
            <block class="Magento\Framework\View\Element\Text" name="gs.font.awesome.js.include">
                <action method="setText">
                    <argument translate="true" name="text" xsi:type="string">
                        <![CDATA[
                            <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.css" />
                            <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.3.5/jquery.fancybox.min.js"></script>
                        ]]>
                    </argument>
                </action>
            </block>
        </referenceBlock>
    </body>
</page>

Then add this markup to your template file, replacing your images, respectively.

<a data-fancybox="gallery" href="big_1.jpg"><img src="small_1.jpg"></a>
<a data-fancybox="gallery" href="big_2.jpg"><img src="small_2.jpg"></a>

Fancy Box docs

Related Topic