Written by Giles Bennett
On a (relatively) recently rolled-out site we are looking at a series of continual small improvements, the latest of which was a popup calculator to work out the number of tiles required to cover a certain area, and then automatically add the relevant number of tiles to the visitor's basket if so desired.
Whilst, of course, one can easily add Fancybox, or any one of the myriad of other lightbox solutions out there to the via a free or paid extension, there exists the constant threat of plugin creep, where more and more solutions are bolted on when, in reality, doing it in a much simpler fashion is probably the easiest way to implement it. In this post, we look at how to quickly and easily implement Fancybox into your site.
The first step is to download the latest version of Fancybox (version 3) from their website and unzip it. Within the myriad of folders you will find one called dist, and within that you will find four files - the CSS file (and a minified version) and the JS file (and a minified version.
Upload those to your Magento installation - you want to put them in the relevant place within your theme's folder, which will be :
app/design/frontend/Package/Theme/Magento_Theme/web/css
and
app/design/frontend/Package/Theme/Magento_Theme/web/js
If, by some odd chance, those directories don't exist, create them.
Next, we need to tell Magento to load the Fancybox script. To do that, within the
app/design/frontend/Package/Theme/Magento_Theme/
directory you will need to edit, or create if it does not exist, a file called requirejs-config.js
Within that you will want to put :
var config = {
paths: {
'fancybox': "js/jquery.fancybox.min"
},
shim: {
'fancybox': {
deps: ['jquery']
}
}
};
That firstly tells Magento where to look for the script (inside the web/js folder), and then tells it that it is dependant upon jQuery to run.
Finally, we need to edit
app/design/frontend/Package/Theme/Magento_Theme/layout/default_head_blocks.xml
to tell Magento to load the CSS file on every page. Again, this is easy enough to do just by adding in a line for the new CSS file - there will almost certainly be some CSS lines of CSS in there already, but on the exceedingly unlikely chance there are not, you will want to end up with something along these lines :
<?xml version="1.0"?>
<!--
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
-->
<page xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
<head>
<css src="css/jquery.fancybox.css" />
</head>
</page>
And that's done. Now, within your PHTML file or CMS block you can simply line up your Fancybox script
<script type="text/javascript">
require(['jquery','fancybox'], function($) {
// Do anything you need to here.
})
</script>
and use Fancybox's functionality as you would on any other site.