41

I am using colorbox in a responsive website.

I have a request : I wish that Colorbox automatically adjusts itself to the size and orientation of the screen / mobile device : if I change the orientation of the screen / mobile device (ie if I rotate my mobile to adjust horizontal and vertival pictures to the screen size, I wish that Colorbor automatically adjusts itself to the new size / orientation of the screen). for now, Colorbox only automatically adjusts itself on load of a new picture (in a slideshow for exemple).

I asked the question in the closed google group :

https://groups.google.com/group/colorbox/browse_thread/thread/85b8bb2d8cb0cc51?hl=fr

I created two feature requests on github :

https://github.com/jackmoore/colorbox/issues/158

but I don't have any response, so I try on Stack Overflow...

Does anyone know if it's possible to get ColorBox to auto-resize based on orientation change (maybe with a callback function in a workaround)?

starball
  • 20,030
  • 7
  • 43
  • 238
vincent3569
  • 447
  • 1
  • 4
  • 9

17 Answers17

63

I solved it using the maxWidth and maxHeight options on colorbox initialization, as explained on the developer's website :

jQuery(*selector*).colorbox({maxWidth:'95%', maxHeight:'95%'});

You can also add this snippet to resize the colorbox when resizing the window or changing your mobile device's orientation :

/* Colorbox resize function */
var resizeTimer;
function resizeColorBox()
{
    if (resizeTimer) clearTimeout(resizeTimer);
    resizeTimer = setTimeout(function() {
            if (jQuery('#cboxOverlay').is(':visible')) {
                    jQuery.colorbox.load(true);
            }
    }, 300)
}

// Resize Colorbox when resizing window or changing mobile device orientation
jQuery(window).resize(resizeColorBox);
window.addEventListener("orientationchange", resizeColorBox, false);

Eventually, replace jQuery by $ .

NicolasBernier
  • 1,586
  • 14
  • 15
  • 5
    load method is not publicly accessible any longer. So use `jQuery.colorbox.resize()` method instead of `load` method and pass the width and height as an object. eg: `jQuery.colorbox.resize(width:'90%', height:'90%')` – Shabith Oct 25 '13 at 04:35
  • 8
    @Shabith You are missing the curly brackets there - It should be `jQuery.colorbox.resize({width:'90%', height:'90%'})` – ckhatton Nov 15 '13 at 04:08
37

I tried many of the solutions here but the following from @berardig on github worked really well for me

var cboxOptions = {
  width: '95%',
  height: '95%',
  maxWidth: '960px',
  maxHeight: '960px',
}

$('.cbox-link').colorbox(cboxOptions);

$(window).resize(function(){
    $.colorbox.resize({
      width: window.innerWidth > parseInt(cboxOptions.maxWidth) ? cboxOptions.maxWidth : cboxOptions.width,
      height: window.innerHeight > parseInt(cboxOptions.maxHeight) ? cboxOptions.maxHeight : cboxOptions.height
    });
});

Source: https://github.com/jackmoore/colorbox/issues/183#issuecomment-42039671

jzahedieh
  • 1,570
  • 1
  • 15
  • 27
  • 2
    This should be the accepted answer. It's simple, not hackish and it offers all desired options. I've been using colorbox in responsive projects for a long time - and this solution beats all others. Thanks! – Simon Steinberger Nov 19 '14 at 07:05
  • 2
    You can make it even shorter by using integers for maxWidth/maxHeight. Thus parseInt gets redundant without loss of functionality. – Simon Steinberger Nov 19 '14 at 07:07
10

Looks like this issue has been discussed and working solutions offered on the author's github

https://github.com/jackmoore/colorbox/issues/158

chrisrth
  • 1,182
  • 3
  • 15
  • 36
3

Call this on window resize and/or "orientationchange" Where 960 is the preferred width for my colorbox, and my maxWidth = 95%

var myWidth = 960, percentageWidth = .95;       
if ($('#cboxOverlay').is(':visible')) {         
    $.colorbox.resize({ width: ( $(window).width() > ( myWidth+20) )? myWidth : Math.round( $(window).width()*percentageWidth ) });
    $('.cboxPhoto').css( {
        width: $('#cboxLoadedContent').innerWidth(),
        height: 'auto'
    });
    $('#cboxLoadedContent').height( $('.cboxPhoto').height() );
    $.colorbox.resize();

}
Ray
  • 49
  • 2
3

Add this into your main js file after load the color box related js and jquery lib files.

(function ($, window, document, undefined) {
//Configure colorbox call back to resize with custom dimensions 
  $.colorbox.settings.onLoad = function() {
    colorboxResize();
  }

  //Customize colorbox dimensions
  var colorboxResize = function(resize) {
    var width = "90%";
    var height = "90%";

if($(window).width() > 960) { width = "860" }
if($(window).height() > 700) { height = "630" } 

$.colorbox.settings.height = height;
$.colorbox.settings.width = width;

//if window is resized while lightbox open
if(resize) {
  $.colorbox.resize({
    'height': height,
    'width': width
      });
    } 
  }

    //In case of window being resized
  $(window).resize(function() {
    colorboxResize(true);
  });

})(jQuery, this, this.document);
Sumith Harshan
  • 6,325
  • 2
  • 36
  • 35
  • 1
    Thank you very much brother. This is the best Responsive solution for colorbox. Just put above code at the end of jquery.colorbox.js file and it solves the problem. – G_real Jun 05 '19 at 20:14
2

You should consider 'framing' with @media query colorBox css file the same way you'd do with the rest of your css.

Milche Patern
  • 19,632
  • 6
  • 35
  • 52
2

This one is working properly brothers.

jQuery( document ).ready( function(){
var custom_timeout = ( function() {
    var timers = {};
    return function ( callback, ms, uniqueId ) {
        if ( !uniqueId ) {
            uniqueId = "Don't call this twice without a uniqueId";
        }
        if ( timers[uniqueId] ) {
            clearTimeout ( timers[uniqueId] );
        }
        timers[uniqueId] = setTimeout( callback, ms );
      };
})(); 
$(".group1").colorbox({rel:'group1', width:"80%" }); 
$( window ).resize( function(){
    custom_timeout(function(){
        if( $('#cboxOverlay' ).css( 'visibility' ) ){
            $(".group1").colorbox.resize({ innerWidth:'80%' });
        }
    }, 500 );
}); 

});

Visit demo page

Anthony Carbon
  • 608
  • 1
  • 5
  • 18
2

In the jQuery.colorbox.js file just make this change

line 24:-

maxWidth: "100%",

Don't make any other changes, all will be working fine with all responsive effect :)

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Richardsan
  • 21
  • 1
1

I've made this in CSS for youtube video box, but take care, it could cut some vertical images.

@media (max-width: 480px) {
#colorbox {
max-height:218px !important;
}
#cboxWrapper *, #cboxWrapper {
height:auto !important;
}
}
Iggy
  • 2,014
  • 25
  • 21
1

This is the solution that worked for me, I took out the timer stuff that was originally posted by Shabith.

    /**
     * Auto Re-Size function
     */
    function resizeColorBox()
    {
        if (jQuery('#cboxOverlay').is(':visible')) {
            jQuery.colorbox.resize({width:'100%', height:'100%'});
        }
    }

    // Resize Colorbox when resizing window or changing mobile device orientation
    jQuery(window).resize(resizeColorBox);
    window.addEventListener("orientationchange", resizeColorBox, false);

Credits go to: shabith

HappyCoder
  • 5,985
  • 6
  • 42
  • 73
1

Here is the best solution I ever used on this issue even if you are using CDNs to integrate color-box

in the header where you added your scripts to integrate your color-box just add this before the script start

// Make ColorBox responsive
    jQuery.colorbox.settings.maxWidth  = '95%';
    jQuery.colorbox.settings.maxHeight = '95%';

    // ColorBox resize function
    var resizeTimer;
    function resizeColorBox()
    {
        if (resizeTimer) clearTimeout(resizeTimer);
        resizeTimer = setTimeout(function() {
                if (jQuery('#cboxOverlay').is(':visible')) {
                        jQuery.colorbox.load(true);
                }
        }, 300);
    }

    // Resize ColorBox when resizing window or changing mobile device orientation
    jQuery(window).resize(resizeColorBox);
    window.addEventListener("orientationchange", resizeColorBox, false);
Yousef Altaf
  • 2,631
  • 4
  • 46
  • 71
0

A solution I found on the Drupal site uses Colorbox's OFF function:

if (window.matchMedia) {
    // Establishing media check
    width700Check = window.matchMedia("(max-width: 700px)");
    if (width700Check.matches){
        $.colorbox.remove();
    }
}

You would need to re-initiate colorbox over a certain window size.

Duncanmoo
  • 3,535
  • 2
  • 31
  • 32
0

My solution, helps when the website is not responsive and you want the colorbox to be visible on mobile devices. I personally use it to store reCaptcha form, so it's obligatory.

    if( /Android|webOS|iPhone|iPad|iPod|BlackBerry/i.test(navigator.userAgent) ) {
        $.colorbox({reposition: true, top: 0, left: 0, transition: 'none', speed:'50', inline:true, href:"#contactus"}).fadeIn(100);
    } else {
        $.colorbox({width:"400px", height:"260px", transition: 'none', speed:'50', inline:true, href:"#contactus"}).fadeIn(100);
    }
Wojtek Zeglin
  • 106
  • 1
  • 10
0

Before colorbox js lock, insert the following code:

jQuery.colorbox.settings.maxWidth  = '95%';
jQuery.colorbox.settings.maxHeight = '95%';

var resizeTimer;
function resizeColorBox()
  {
      if (resizeTimer) clearTimeout(resizeTimer);
      resizeTimer = setTimeout(function() {
              if (jQuery('#cboxOverlay').is(':visible')) {
                      jQuery.colorbox.load(true);
              }
      }, 300);
  }
jQuery(window).resize(resizeColorBox);
window.addEventListener("orientationchange", resizeColorBox, false);

Leave left, right, bottom and top with value 'false' and it will do the calculation automatically. It worked for me so I'm going over!

0

I would like to add an answer here. I had a requirement to make the colorbox responsive by respecting different breakpoint widths and change the width of the popover based on window width. Basically, I can afford to have empty spaces to the left and right of the colorbox when it is displayed in a browser but not when it is displayed in a phone / tablet.

I have used the concept of an answer from this very post (https://stackoverflow.com/a/23431190/260665) but made few modifications:

/**
 * Raj: Used basic source from here: https://stackoverflow.com/a/23431190/260665
 **/

// Make sure the options are sorted in descending order of their breakpoint widths
var cboxDefaultOptions = 
        [   
            {
                breakpointMinWidth: 1024,
                values: {
                    width : '70%',
                    maxWidth : '700px',
                }
            },
            {
                breakpointMinWidth: 640,
                values: {
                    width : '80%',
                    maxWidth : '500px',
                }
            },
            {
                breakpointMinWidth: 320,
                values: {
                    width : '95%',
                    maxWidth : '300px',
                }
            }
        ];

$(window).resize(function(){
//  alert (JSON.stringify($.colorbox.responsiveOptions));
//  var respOpts = $.colorbox.attr('responsiveOptions');
    var respOpts = $.colorbox.responsiveOptions;
    if (respOpts) {
        var breakpointOptions = breakpointColorboxOptionsForWidth (window.innerWidth);
        if (breakpointOptions) {
            $.colorbox.resize({
                width: window.innerWidth > parseInt(breakpointOptions.values.maxWidth) ? breakpointOptions.values.maxWidth : breakpointOptions.values.width,
              });
        }
    }
});

function breakpointColorboxOptionsForWidth (inWidth) {
    var breakpointOptions = null;
    for (var i=0; i<cboxDefaultOptions.length; i++) {
        var anOption = cboxDefaultOptions[i];
        if (inWidth >= anOption.breakpointMinWidth) {
            breakpointOptions = anOption;
            break;
        }
    }
    return breakpointOptions;
}

Usage:

        $.colorbox.responsiveOptions = cboxDefaultOptions;

When the colorbox object is prepared just add this additional attribute to it. We can also configure cboxDefaultOptions or supply a different custom valued object to $.colorbox.responsiveOptions so that it loads with different breakpoints if needed.

Community
  • 1
  • 1
Raj Pawan Gumdal
  • 7,390
  • 10
  • 60
  • 92
0

Answer from owner of colorbox.

window.addEventListener("orientationchange", function() {
if($('#cboxOverlay').is(':visible'){
    $.colorbox.load(true);
}
}, false);
Abasaheb Gaware
  • 509
  • 4
  • 13
  • The owner of colorbox removed the `load()` function from the public API in 1.4.5 and this answer no longer works. For the continuing discussion and possible solutions: https://github.com/jackmoore/colorbox/issues/158 – JPMC Nov 17 '17 at 20:07
0

I found a solution combining several solutions I found on StackOverflow and GitHub:

  jQuery(function($) {
    var config = {
        maxWidth: 0.95,
        maxHeight: 0.95
    }
    
    // Contao default code
    $('a[data-lightbox]').map(function() {
        $(this).colorbox({
            rel: $(this).attr('data-lightbox'),
            maxWidth: (config.maxWidth * 100).toString() + '%',
            maxHeight: (config.maxHeight * 100).toString() + '%',
            fixed: true
        });
    });
    
    // Yousef Altaf 's solution
    var resizeTimer = null;
    var resizeTimeout = 300;
    function resizeColorBox()
    {
        clearTimeout(resizeTimer);
        
        resizeTimer = setTimeout(function() {
            if ($('#cboxOverlay').is(':visible')) {
                    $.colorbox.resize({
                        maxWidth: config.maxWidth * 100 + '%',
                        maxHeight: config.maxHeight * 100 + '%'
                    });
                    
                    // my addition:
                    // get the original size of the image
                    var photo = $('.cboxPhoto');
                    var imgWidth = photo.prop('naturalWidth');
                    var imgHeight = photo.prop('naturalHeight');
                    if (!(isNaN(imgWidth) || isNaN(imgHeight))) { // only if its an image and HTML5 properties work as expected
                        var windowWidth = $(window).width();
                        var windowHeight = $(window).height();
            
                        // get the max available space for the image content
                        // -> substract border width (2*5px)
                        // -> substract title column height (20px)
                        var maxWidth = Math.round((windowWidth * config.maxWidth) - 10);
                        var maxHeight = Math.round((windowHeight * config.maxHeight) - 30);
                        
                        // Calculate aspect ratio for available space and original image size
                        var contentAspect = maxWidth / maxHeight;
                        var photoAspect = imgWidth / imgHeight;
                        
                        var height;
                        var width;
                        if (photoAspect > contentAspect) {
                            // max out new width, use image width if its less than max available width
                            var size = maxWidth > imgWidth ? imgWidth : maxWidth;
                            var width = size + 'px';
                            var height = size / photoAspect + 'px';
                        } else {
                            // max out new height, use image height if its smaller than max available height
                            var size = maxHeight > imgHeight ? imgHeight : maxHeight;
                            var height = size + 'px';
                            var width = size * photoAspect + 'px';
                        }
                        
                        // set the new dimensions as inner size
                        $.colorbox.resize({
                            innerHeight: height,
                            innerWidth: width
                        });
                        // scale the photo as this is not done by colorbox when resizing
                        $('.cboxPhoto').css({
                            width: width,
                            height: height
                        })
                    }
            }
        }, resizeTimeout)
    }
    
    // Resize Colorbox when resizing window or changing mobile device orientation
    $(window).resize(resizeColorBox);
    window.addEventListener("orientationchange", resizeColorBox, false);
  });

This code originates fom the Contao j_colorbox template. I customized this code with the proposed solution of Yousef Altaf but wasn't satisfied with the image sizing, though it solved the problem with the colorbox getting stuck at the edge of the screen.

To fix the issue with the image not benefiting from increased space/not respecting reduced space I added some code to resize the box again according to maximum available size and image aspect ratio. However, this relies on HTM5 properties, as described here, so I added a guard to prevent issues on older browsers.

Edit:

I found this one useful too: https://stackoverflow.com/a/8697415/12390988https://stackoverflow.com/a/8697415/12390988

Also i included a fullscreen-mode on mobile devices:

    $('a[data-lightbox]').map(function() {
        // Not 100% reliable but ok for the usecase i think
        var isMobile = /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
        var fullscreenActiveBeforeOpen = false;
        
        $(this).colorbox({
            rel: $(this).attr('data-lightbox'),
            maxWidth: (config.maxWidth * 100).toString() + '%',
            maxHeight: (config.maxHeight * 100).toString() + '%',
            fixed: true,
            loop: false, 
            onLoad: function() {
                $('html, body').css('overflow', 'hidden'); // page scrollbars off
                // On mobile devices, enter fullscreen
                if (isMobile) {
                    // Remember fullscreen state before opening
                    fullscreenActiveBeforeOpen = !!document.fullscreenElement;
                    document.documentElement.requestFullscreen();
                }
            }, 
            onClosed: function() {
                $('html, body').css('overflow', ''); // page scrollbars on
                // On mobile devices and if fullscreen has not been active before, end fullscreen
                if (isMobile && !fullscreenActiveBeforeOpen) {
                    document.exitFullscreen();
                }
            }
        });
    });

Edit 2:

I found that the fullscreen-code breaks on at least some IOS devices because requestFullscreen is missing. Wrapping the fullscreen API with try/catch prevents the colorbox from breaking/freezing; Using webkitRequestFullscreen, webkitFullscreenEnabled and webkitExitFullscreen enables fullscreen on Safari:

        // snip...

        var fullscreenBroken = false;
        
        $(this).colorbox({
            rel: $(this).attr('data-lightbox'),
            maxWidth: (config.maxWidth * 100).toString() + '%',
            maxHeight: (config.maxHeight * 100).toString() + '%',
            fixed: true,
            loop: false, 
            onLoad: function() {
                $('html, body').css('overflow', 'hidden'); // page scrollbars off
                if (isMobile && !fullscreenBroken) {
                    try {
                        fullscreenActiveBeforeOpen = typeof document.webkitFullscreenEnabled === 'boolean' 
                            ? document.webkitFullscreenEnabled
                            : !!document.fullscreenEnabled;
                        typeof document.documentElement.webkitRequestFullscreen === 'function'
                            ? document.documentElement.webkitRequestFullscreen()
                            : document.documentElement.requestFullscreen();
                    } catch (e) {
                        fullscreenBroken = true
                    }
                }
            }, 
            onClosed: function() {
                $('html, body').css('overflow', ''); // page scrollbars on
                if (isMobile && !fullscreenActiveBeforeOpen && !fullscreenBroken) {
                    try {
                        typeof document.webkitExitFullscreen === 'function'
                            ? document.webkitExitFullscreen()
                            : document.exitFullscreen();
                    } catch (e) {
                        fullscreenBroken = true
                    }
                }
            }
        });

        // snip...
gabelbart
  • 73
  • 7