Magento – How to display fancybox popup when page load in magento2

frontendmagento2popup

I want to display popup using fancybox when page load in magento2 . How is it possible ?

Please help me….

    <!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
require([ 'jquery', 'jquery/ui','fancybox'],  function( $ ) {

     $(document).ready(function() {
        $.fancybox("#hidden");
        //alert("a");
    });

}); 
</script>
</head>
<body>
<div id="hidden" style="display:none;">
    Hi this is hidden
</div>

</body>
</html>

Best Answer

For Exmaple: I used magnify popup to display popup on load page

Namespace: Prince

ModuleName: Popup

1) First of all put js and css files of your popup in web folder of module

app/code/Prince/Popup/view/frontend/web/js/jquery.magnific-popup.min.js
app/code/Prince/Popup/view/frontend/web/css/magnific-popup.css

2) Now define your custom popup js in requirejs-config.js or create new requirejs-config.js file

app/code/Prince/Popup/view/frontend/requirejs-config.js

var config = {
    map: {
        '*': {
            magnificPopup: 'Prince_Popup/js/jquery.magnific-popup.min',       
        }
    },
    shim: {
        magnificPopup: {
            deps: ['jquery']
        }
    }
};

3) Now create template file for popup

app/code/Prince/Popup/view/frontend/templates/index/popup.phtml

<div id="popup-content" class="popup-content mfp-with-anim">
Your Poup Content...............
</div>

<script type="text/javascript">
  requirejs(['jquery', 'magnificPopup' ],
    function ($, magnificPopup) {
        $(document).ready(function(){
            $.magnificPopup.open({
              items: {
                src: '#popup-content'
                },
                type: 'inline',
                removalDelay: 500,
                mainClass: 'mfp-newspaper'
              });
            $('#popup-content').css('display','inline block');
        });
    });
</script>

4) Inject this template file in xml where you need to show popup

for exmaple to show popup on home page. ovveride cms_index_index.xml

<?xml version="1.0" ?>
<page layout="1column" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <link src="Prince_Popup/js/jquery.magnific-popup.min.js"/>
        <css src="Prince_Popup/css/magnific-popup.css"/>
    </head>
    <body>
        <referenceContainer name="content">
            <block class="Magento\Framework\View\Element\Template" name="index.home" template="Prince_Popup::index/popup.phtml"/>
        </referenceContainer>
    </body>
</page>