Search code examples
jqueryfancyboxfancybox-2

Fancybox: different width percentages - cleaner script?


I needed a 100% fancybox width for mobiles and 90% width for greater screens. I did tweak the common script and it's working but I know it looks like a troglodyte scripting:

           if (windowWidth > 480) {
              $(".fancybox").fancybox({
                  openEffect  : 'none',
                  closeEffect : 'none',
                  iframe : {
                      preload: false
                  },
                  padding: 0,
                  width : '90%',
                  height : '90%',
                  helpers : {
                    overlay : {
                        css : {
                            'background' : 'rgba(0, 0, 0, 0.65)'
                        }
                    }
                  }
              });
          }else{
              $(".fancybox").fancybox({
                  openEffect  : 'none',
                  closeEffect : 'none',
                  iframe : {
                      preload: false
                  },
                  padding: 0,
                  width : '100%',
                  height : '90%',
                  helpers : {
                    overlay : {
                        css : {
                            'background' : 'rgba(0, 0, 0, 0.65)'
                        }
                    }
                  }
              });
        }

So, I'd like to know how to separete the width and height to avoid the "duplicated" definition.


Solution

  • Just place your conditional statement inside the fancybox afterLoad callback like :

    afterLoad: function () {
        if (window.innerWidth > 480) {
            this.width = '90%'; // or whatever
            this.height = '90%';
        } else {
            this.width = '100%';
            this.height = '90%';
        }
    }
    

    Notice that, in order to get your custom dimensions, you may need to set the fitToView option to false. You may also need to adjust the fancybox margins.

    See JSFIDDLE