Member Avatar for sonicx2218

So I'm using mediabox which creates lightbox Iframes. I've modded it quite a bit, and there's just ONE last thing I want to accomplish. When the "popup" occurs, my site is still loading in the iframe; the process looks unproffesional. I have 2 key pieces of code, and I was wondering how I could manage having the app wait a little bit before showing the iframe site, so it has a headstart on loading?

This states the duration of the effect, but the page waits until it is finished to start loading.

resizeOpening: true,            // Determines if box opens small and grows (true) or starts at larger size (false)
resizeDuration: 200,            // Duration of each of the box resize animations (in milliseconds)
resizeTransition: false,        // Mootools transition effect (false leaves it at the default)

This here basically sets up the iframe. I'm wondering if I can put the preload before everything else and I'd get the result I'm after. Please let me know.

else {
                mediaType = 'url';
                mediaWidth = mediaWidth || "638px";
                mediaHeight = mediaHeight || "1000px";
                mediaId = "mediaId_"+new Date().getTime();  // Safari may not update iframe content with a static id.
                preload = new Element('iframe', {
                    'src': URL,
                     'id': mediaId,
                     width: mediaWidth,
                     height: mediaHeight,
                     scrolling : 'no',
                     'frameborder': 0
                    });
                startEffect();
            }

This loads the iframe in the lightbox.

else if (mediaType == "url") {
            image.setStyles({backgroundImage: "none", display: ""});
            preload.inject(image);
        }

Any help with this dilemna is appreciated, but I understand that it's not simple.

Recommended Answers

All 10 Replies

When the "popup" occurs, my site is still loading in the iframe; the process looks unproffesional.

so you want to look professional..., good! What is your dilemma?

Member Avatar for sonicx2218

I want the site loading in the iframe to load during the player resizing & opening sequence, and not after all is finished like it currently does. To get an idea, here's a throwaway site with the code in place.
http://www.scatterset.com/#!test/c6o3

Ideally, the iframe site would already have 2 seconds of load time in before it appears, instead of showing it the moment it starts loading. It's hard to describe in text.

I want the site loading in the iframe to load during the player resizing & opening sequence

Start loading the iframe source before "the player resizing & opening sequence" command is issued.

Member Avatar for sonicx2218

It's really weird. I've tried a bunch of attempts at that, and all they achieved was either the content not showing up at all, or in a really small box

Member Avatar for sonicx2218

Preload.inject seems to place the iframe setup in the 2nd code, but it's still after everything else. If I include the full code, is someone willing to look into it?

IFrames do not resize happily with javascript, last I tried it...

You may need to force attribute changes by doing iFrame.setAttribute("height", number); //you may need number+"px" I forget

Member Avatar for sonicx2218

The Iframe works exactly as I wanted. The program is 100% functional. The only thing I'm trying to change is either hiding the iframe site from appearing for a sec or 2 so that the user doesn't have to see everything on the page load one by one, OR make the iframe page load while the lightbox is opening. The first seems more possible, but I'm not a pro at this.

Im not very familliar with mootools, so I will explain what I would do in JS and hopefully you can translate it.

an IFrame doesn't have to be visible to load data, and an IFrame has a .onload trigger. So... you can have the default inline style of the iframe to visibility:hidden; (note, not display:none;), and use the iframe's onload to run a function that simply flips the switch (i.e., iframe.style.visibility = ""; )

Without knowing the full order of loading, it's a bit difficult to tell you how to do it... it may be that on your parent page you need a function that does the visibility="" for you, and you have to put the onload on the body of the iframe content using something like...

function doShow()
{
  if (parent.showFunction) { parent.showFunction(); }; 
}

document.body.onload = doShow();

or if you want to be fully compliant you can add the event handler in your flavor of choice...

Hope that helps..

Ryan

note... you may need to tweak that code a bit... Im pretty sure that if you don't have a document body at run time, that will error out... so you can either put that code all the way at the bottom of the page, or just make sure the body is available to attach a handler.

Member Avatar for sonicx2218

OO ok that makes a lot of sense. Thanks, I'll work on figuring out how I can apply that to this code. Here's the full set if you're daring, but it's a lot so I'm not expecting it.

var Mediabox;

(function() {
    // Global variables, accessible to Mediabox only
    var options, images, activeImage, prevImage, nextImage, top, mTop, left, mLeft, winWidth, winHeight, fx, preload, preloadPrev = new Image(), preloadNext = new Image(), foxfix = false, iefix = false,
    // DOM elements
    overlay, center, image, bottom, captionSplit, title, caption, prevLink, number, nextLink,
    // Mediabox specific vars
    URL, WH, WHL, elrel, mediaWidth, mediaHeight, mediaType = "none", mediaSplit, mediaId = "mediaBox", mediaFmt, margin;

    /*  Initialization  */

    window.addEvent("domready", function() {
        // Create and append the Mediabox HTML code at the bottom of the document
        document.id(document.body).adopt(
            $$([
                overlay = new Element("div", {id: "mbOverlay"}).addEvent("click", close),
                center = new Element("div", {id: "mbCenter"})
            ]).setStyle("display", "none")
        );

        image = new Element("div", {id: "mbImage"}).injectInside(center);
        bottom = new Element("div", {id: "mbBottom"}).injectInside(center).adopt(
            closeLink = new Element("a", {id: "mbCloseLink", href: "#"}).addEvent("click", close),
            nextLink = new Element("a", {id: "mbNextLink", href: "#"}).addEvent("click", next),
            prevLink = new Element("a", {id: "mbPrevLink", href: "#"}).addEvent("click", previous),
            title = new Element("div", {id: "mbTitle"}),
            number = new Element("div", {id: "mbNumber"}),
            caption = new Element("div", {id: "mbCaption"})
        );

        fx = {
            overlay: new Fx.Tween(overlay, {property: "opacity", duration: 400}).set(0),
            image: new Fx.Tween(image, {property: "opacity", duration: 400, onComplete: captionAnimate}),
            bottom: new Fx.Tween(bottom, {property: "opacity", duration: 300}).set(0)
        };
    });

    /*  API     */

    Mediabox = {
        close: function(){
            close();    // Thanks to Yosha on the google group for fixing the close function API!
        },

        open: function(_images, startImage, _options) {
            options = $extend({
                text: ['<big>&laquo;</big>','<big>&raquo;</big>','<big>&times;</big>'],       // Set "previous", "next", and "close" button content (HTML code should be written as entity codes or properly escaped)
//              text: ['<big>«</big>','<big>»</big>','<big>×</big>'],     // Set "previous", "next", and "close" button content (HTML code should be written as entity codes or properly escaped)
//  example     text: ['<b>P</b>rev','<b>N</b>ext','<b>C</b>lose'],
                loop: false,                    // Allows to navigate between first and last images
                keyboard: true,                 // Enables keyboard control; escape key, left arrow, and right arrow
                alpha: true,                    // Adds 'x', 'c', 'p', and 'n' when keyboard control is also set to true
                stopKey: false,                 // Stops all default keyboard actions while overlay is open (such as up/down arrows)
                                                    // Does not apply to iFrame content, does not affect mouse scrolling
                overlayOpacity: .9,         // 1 is opaque, 0 is completely transparent (change the color in the CSS file)
                resizeOpening: true,            // Determines if box opens small and grows (true) or starts at larger size (false)
                resizeDuration: 200,            // Duration of each of the box resize animations (in milliseconds)
                resizeTransition: false,        // Mootools transition effect (false leaves it at the default)
                initialWidth: 320,              // Initial width of the box (in pixels)
                initialHeight: 180,             // Initial height of the box (in pixels)
                defaultWidth: 640,              // Default width of the box (in pixels) for undefined media (MP4, FLV, etc.)
                defaultHeight: 360,             // Default height of the box (in pixels) for undefined media (MP4, FLV, etc.)
                showCaption: true,              // Display the title and caption, true / false
                showCounter: true,              // If true, a counter will only be shown if there is more than 1 image to display
                counterText: '({x} of {y})',    // Translate or change as you wish
//          Image options
                imgBackground: false,       // Embed images as CSS background (true) or <img> tag (false)
                                            // CSS background is naturally non-clickable, preventing downloads
                                            // IMG tag allows automatic scaling for smaller screens
                                            // (all images have no-click code applied, albeit not Opera compatible. To remove, comment lines 212 and 822)
                imgPadding: 100,            // Clearance necessary for images larger than the window size (only used when imgBackground is false)
                                            // Change this number only if the CSS style is significantly divergent from the original, and requires different sizes
//          Inline options
//              overflow: 'auto',           // If set, overides CSS settings for inline content only
//          Global media options
                html5: 'true',              // HTML5 settings for YouTube and Vimeo, false = off, true = on
                scriptaccess: 'true',       // Allow script access to flash files
                fullscreen: 'true',         // Use fullscreen
                fullscreenNum: '1',         // 1 = true
                autoplay: 'true',           // Plays the video as soon as it's opened
                autoplayNum: '1',           // 1 = true
                autoplayYes: 'yes',         // yes = true
                volume: '100',              // 0-100, used for NonverBlaster and Quicktime players
                medialoop: 'true',          // Loop video playback, true / false, used for NonverBlaster and Quicktime players
                bgcolor: '#000000',         // Background color, used for flash and QT media
                wmode: 'opaque',            // Background setting for Adobe Flash ('opaque' and 'transparent' are most common)

//          JW Media Player settings and options
                JWplayerpath: '/js/player.swf', // Path to the mediaplayer.swf or flvplayer.swf file
                backcolor:  '000000',       // Base color for the controller, color name / hex value (0x000000)
                frontcolor: '999999',       // Text and button color for the controller, color name / hex value (0x000000)
                lightcolor: '000000',       // Rollover color for the controller, color name / hex value (0x000000)
                screencolor: '000000',      // Rollover color for the controller, color name / hex value (0x000000)
                controlbar: 'over',         // bottom, over, none (this setting is ignored when playing audio files)

//          Vimeo options
                vmTitle: '1',               // Show video title
                vmByline: '1',              // Show byline
                vmPortrait: '1',            // Show author portrait
                vmColor: 'ffffff'           // Custom controller colors, hex value minus the # sign, defult is 5ca0b5
            }, _options || {});

            prevLink.set('html', options.text[0]);
            nextLink.set('html', options.text[1]);
            closeLink.set('html', options.text[2]);

            margin = center.getStyle('padding-left').toInt()+image.getStyle('margin-left').toInt()+image.getStyle('padding-left').toInt();

            if ((Browser.Engine.gecko) && (Browser.Engine.version<19)) { // Fixes Firefox 2 and Camino 1.6 incompatibility with opacity + flash
                foxfix = true;
                options.overlayOpacity = 1;
                overlay.className = 'mbOverlayFF';
            }

            if ((Browser.Engine.trident) && (Browser.Engine.version<5)) {    // Fixes IE 6 and earlier incompatibilities with CSS position: fixed;
                iefix = true;
                overlay.className = 'mbOverlayIE';
                overlay.setStyle("position", "absolute");
                position();
            }

            if (typeof _images == "string") {   // Used for single images only, with URL and Title as first two arguments
                _images = [[_images,startImage,_options]];
                startImage = 0;
            }

            images = _images;
            options.loop = options.loop && (images.length > 1);

            size();
            setup(true);
            top = window.getScrollTop() + (window.getHeight()/2);
            left = window.getScrollLeft() + (window.getWidth()/2);
            fx.resize = new Fx.Morph(center, $extend({duration: options.resizeDuration, onComplete: imageAnimate}, options.resizeTransition ? {transition: options.resizeTransition} : {}));
            center.setStyles({top: top, left: left, width: options.initialWidth, height: options.initialHeight, marginTop: -(options.initialHeight/2)-margin, marginLeft: -(options.initialWidth/2)-margin, display: ""});
            fx.overlay.start(options.overlayOpacity);
            return changeImage(startImage);
        }
    };

    Element.implement({
        mediabox: function(_options, linkMapper) {
            $$(this).mediabox(_options, linkMapper);    // The processing of a single element is similar to the processing of a collection with a single element

            return this;
        }
    });

    Elements.implement({
        /*
            options:    Optional options object, see Mediabox.open()
            linkMapper: Optional function taking a link DOM element and an index as arguments and returning an array containing 3 elements:
                        the image URL and the image caption (may contain HTML)
            linksFilter:Optional function taking a link DOM element and an index as arguments and returning true if the element is part of
                        the image collection that will be shown on click, false if not. "this" refers to the element that was clicked.
                        This function must always return true when the DOM element argument is "this".
        */
        mediabox: function(_options, linkMapper, linksFilter) {
            linkMapper = linkMapper || function(el) {
                elrel = el.rel.split(/[\[\]]/);
                elrel = elrel[1];
                return [el.href, el.title, elrel];
            };

            linksFilter = linksFilter || function() {
                return true;
            };

            var links = this;

            links.addEvent('contextmenu', function(e){
                if (this.toString().match(/\.gif|\.jpg|\.jpeg|\.png/i)) e.stop();
            });

            links.removeEvents("click").addEvent("click", function() {
                // Build the list of images that will be displayed
                var filteredArray = links.filter(linksFilter, this);
                var filteredLinks = [];
                var filteredHrefs = [];

                filteredArray.each(function(item, index){
                    if(filteredHrefs.indexOf(item.toString()) < 0) {
                        filteredLinks.include(filteredArray[index]);
                        filteredHrefs.include(filteredArray[index].toString());
                    };
                });

                return Mediabox.open(filteredLinks.map(linkMapper), filteredHrefs.indexOf(this.toString()), _options);
            });

            return links;
        }
    });

    /*  Internal functions  */

    function position() {
        overlay.setStyles({top: window.getScrollTop(), left: window.getScrollLeft()});
    }

    function size() {
        winWidth = window.getWidth();
        winHeight = window.getHeight();
        overlay.setStyles({width: winWidth, height: winHeight});
    }

    function setup(open) {
        // Hides on-page objects and embeds while the overlay is open, nessesary to counteract Firefox stupidity
        if (Browser.Engine.gecko) {
            ["object", window.ie ? "select" : "embed"].forEach(function(tag) {
                Array.forEach(document.getElementsByTagName(tag), function(el) {
                    if (open) el._mediabox = el.style.visibility;
                    el.style.visibility = open ? "hidden" : el._mediabox;
                });
            });
        }

        overlay.style.display = open ? "" : "none";

        var fn = open ? "addEvent" : "removeEvent";
        if (iefix) window[fn]("scroll", position);
        window[fn]("resize", size);
        if (options.keyboard) document[fn]("keydown", keyDown);
    }

    function keyDown(event) {
        if (options.alpha) {
            switch(event.code) {
                case 27:    // Esc
                case 88:    // 'x'
                case 67:    // 'c'
                    close();
                    break;
                case 37:    // Left arrow
                case 80:    // 'p'
                    previous();
                    break;
                case 39:    // Right arrow
                case 78:    // 'n'
                    next();
            }
        } else {
            switch(event.code) {
                case 27:    // Esc
                    close();
                    break;
                case 37:    // Left arrow
                    previous();
                    break;
                case 39:    // Right arrow
                    next();
            }
        }
        if (options.stopKey) { return false; };
    }

    function previous() {
        return changeImage(prevImage);
    }

    function next() {
        return changeImage(nextImage);
    }

    function changeImage(imageIndex) {
        if (imageIndex >= 0) {
            image.set('html', '');
            activeImage = imageIndex;
            prevImage = ((activeImage || !options.loop) ? activeImage : images.length) - 1;
            nextImage = activeImage + 1;
            if (nextImage == images.length) nextImage = options.loop ? 0 : -1;
            stop();
            center.className = "mbLoading";

    /*  mediaboxAdvanced link formatting and media support  */

            if (!images[imageIndex][2]) images[imageIndex][2] = ''; // Thanks to Leo Feyer for offering this fix
            WH = images[imageIndex][2].split(' ');
            WHL = WH.length;
            if (WHL>1) {
                mediaWidth = (WH[WHL-2].match("%")) ? (window.getWidth()*((WH[WHL-2].replace("%", ""))*0.01))+"px" : WH[WHL-2]+"px";
                mediaHeight = (WH[WHL-1].match("%")) ? (window.getHeight()*((WH[WHL-1].replace("%", ""))*0.01))+"px" : WH[WHL-1]+"px";
            } else {
                mediaWidth = "";
                mediaHeight = "";
            }
            URL = images[imageIndex][0];
            URL = encodeURI(URL).replace("(","%28").replace(")","%29");
            captionSplit = images[activeImage][1].split('::');

    /*  Specific Media Types    */

// GIF, JPG, PNG
            if (URL.match(/\.gif|\.jpg|\.jpeg|\.png|twitpic\.com/i) || mediaType == 'image') {
                mediaType = 'img';
                URL = URL.replace(/twitpic\.com/i, "twitpic.com/show/full");
                preload = new Image();
                preload.onload = startEffect;
                preload.src = URL;

    /*  Specific Content Types  */

// INLINE
            } else if (URL.match(/\#mb_/i)) {
                mediaType = 'inline';
                mediaWidth = mediaWidth || options.defaultWidth;
                mediaHeight = mediaHeight || options.defaultHeight;
                URLsplit = URL.split('#');
                preload = document.id(URLsplit[1]).get('html');
                startEffect();
// HTML
            } else {
                mediaType = 'url';
                mediaWidth = mediaWidth || "638px";
                mediaHeight = mediaHeight || "1000px";
                mediaId = "mediaId_"+new Date().getTime();  // Safari may not update iframe content with a static id.
                preload = new Element('iframe', {
                    'src': URL,
                     'id': mediaId,
                     width: mediaWidth,
                     height: mediaHeight,
                     scrolling : 'no',
                     'frameborder': 0
                    });
                startEffect();
            }
        }
        return false;
    }

    function startEffect() {
        if (mediaType == "img"){
            mediaWidth = preload.width;
            mediaHeight = preload.height;
            if (options.imgBackground) {
                image.setStyles({backgroundImage: "url("+URL+")", display: ""});
            } else {    // Thanks to Dusan Medlin for fixing large 16x9 image errors in a 4x3 browser
                if (mediaHeight >= winHeight-options.imgPadding && (mediaHeight / winHeight) >= (mediaWidth / winWidth)) {
                    mediaHeight = winHeight-options.imgPadding;
                    mediaWidth = preload.width = parseInt((mediaHeight/preload.height)*mediaWidth);
                    preload.height = mediaHeight;
                } else if (mediaWidth >= winWidth-options.imgPadding && (mediaHeight / winHeight) < (mediaWidth / winWidth)) {
                    mediaWidth = winWidth-options.imgPadding;
                    mediaHeight = preload.height = parseInt((mediaWidth/preload.width)*mediaHeight);
                    preload.width = mediaWidth;
                }
                if (Browser.Engine.trident) preload = document.id(preload);
                preload.addEvent('mousedown', function(e){ e.stop(); }).addEvent('contextmenu', function(e){ e.stop(); });
                image.setStyles({backgroundImage: "none", display: ""});
                preload.inject(image);
            }
        } else if (mediaType == "obj") {
            if (Browser.Plugins.Flash.version<8) {
                image.setStyles({backgroundImage: "none", display: ""});
                image.set('html', '<div id="mbError"><b>Error</b><br/>Adobe Flash is either not installed or not up to date, please visit <a href="http://www.adobe.com/shockwave/download/download.cgi?P1_Prod_Version=ShockwaveFlash" title="Get Flash" target="_new">Adobe.com</a> to download the free player.</div>');
                mediaWidth = options.DefaultWidth;
                mediaHeight = options.DefaultHeight;
            } else {
                image.setStyles({backgroundImage: "none", display: ""});
                preload.inject(image);
            }
        } else if (mediaType == "qt") {
            image.setStyles({backgroundImage: "none", display: ""});
            preload;
        } else if (mediaType == "inline") {
//          if (options.overflow) image.setStyles({overflow: options.overflow});
            image.setStyles({backgroundImage: "none", display: ""});
            image.set('html', preload);
        } else if (mediaType == "url") {
            image.setStyles({backgroundImage: "none", display: ""});
            preload.inject(image);
        } else {
            image.setStyles({backgroundImage: "none", display: ""});
            image.set('html', '<div id="mbError"><b>Error</b><br/>A file type error has occoured, please visit <a href="iaian7.com/webcode/mediaboxAdvanced" title="mediaboxAdvanced" target="_new">iaian7.com</a> or contact the website author for more information.</div>');
            mediaWidth = options.defaultWidth;
            mediaHeight = options.defaultHeight;
        }
        image.setStyles({width: mediaWidth, height: mediaHeight});
        caption.setStyles({width: mediaWidth});

        title.set('html', (options.showCaption) ? captionSplit[0] : "");
        caption.set('html', (options.showCaption && (captionSplit.length > 1)) ? captionSplit[1] : "");
        number.set('html', (options.showCounter && (images.length > 1)) ? options.counterText.replace(/{x}/, activeImage + 1).replace(/{y}/, images.length) : "");

        if ((prevImage >= 0) && (images[prevImage][0].match(/\.gif|\.jpg|\.jpeg|\.png|twitpic\.com/i))) preloadPrev.src = images[prevImage][0].replace(/twitpic\.com/i, "twitpic.com/show/full");
        if ((nextImage >= 0) && (images[nextImage][0].match(/\.gif|\.jpg|\.jpeg|\.png|twitpic\.com/i))) preloadNext.src = images[nextImage][0].replace(/twitpic\.com/i, "twitpic.com/show/full");

        mediaWidth = image.offsetWidth;
        mediaHeight = image.offsetHeight+bottom.offsetHeight;
        if (mediaHeight >= top+top) { mTop = -top } else { mTop = -(mediaHeight/2) };
        if (mediaWidth >= left+left) { mLeft = -left } else { mLeft = -(mediaWidth/2) };
        if (options.resizeOpening) { fx.resize.start({width: mediaWidth, height: mediaHeight, marginTop: mTop-margin, marginLeft: mLeft-margin});
        } else { center.setStyles({width: mediaWidth, height: mediaHeight, marginTop: mTop-margin, marginLeft: mLeft-margin}); imageAnimate(); }
    }

    function imageAnimate() {
        fx.image.start(1);
    }

    function captionAnimate() {
        center.className = "";
        if (prevImage >= 0) prevLink.style.display = "";
        if (nextImage >= 0) nextLink.style.display = "";
        fx.bottom.start(1);
    }

    function stop() {
        if (preload) preload.onload = $empty;
        fx.resize.cancel();
        fx.image.cancel().set(0);
        fx.bottom.cancel().set(0);
        $$(prevLink, nextLink).setStyle("display", "none");
    }

    function close() {
        if (activeImage >= 0) {
            preload.onload = $empty;
            image.set('html', '');
            for (var f in fx) fx[f].cancel();
            center.setStyle("display", "none");
            fx.overlay.chain(setup).start(0);
        }
        return false;
    }
})();

    /*  Autoload code block */

Mediabox.scanPage = function() {
//  $$('#mb_').each(function(hide) { hide.set('display', 'none'); });
    var links = $$("a").filter(function(el) {
        return el.rel && el.rel.test(/^lightbox/i);
    });
    $$(links).mediabox({/* Put custom options here */}, null, function(el) {
        var rel0 = this.rel.replace(/[[]|]/gi," ");
        var relsize = rel0.split(" ");
        return (this == el) || ((this.rel.length > 8) && el.rel.match(relsize[1]));
    });
};
window.addEvent("domready", Mediabox.scanPage);
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.