[jquery] How to launch jQuery Fancybox on page load?

I would like to launch a Fancybox (e.g. Fancybox's version of a modal or light box) on page load. I could bind it to a hidden anchor tag and fire the click event of that anchor tag via JavaScript, but I would rather just launch the Fancybox directly and avoid the extra anchor tag.

This question is related to jquery jquery-plugins fancybox

The answer is


Window.load (as opposed to document.ready()) appears to the be the trick used in the JSFiddler onload demos of Fancybox 2.0:

$(window).load(function()
{
    $.fancybox("test");
});

Bare in mind you may be using document.ready() elsewhere, and IE9 gets upset with the load order of the two. This leaves you with two options: change everything to window.load or use a setTimer().


Its simple:

Make your element hidden first like this:

<div id="hidden" style="display:none;">
    Hi this is hidden
</div>

Then call your javascript:

<script type="text/javascript">
    $(document).ready(function() {
        $.fancybox("#hidden");
    });
</script>

Check out the image below:

enter image description here

Another example:

<div id="example2" style="display:none;">
        <img src="http://theinstitute.ieee.org/img/07tiProductsandServicesiStockphoto-1311258460873.jpg" />
    </div>

 <script type="text/javascript">
        $(document).ready(function() {
            $.fancybox("#example2");
        });
    </script>

enter image description here


I got this to work by calling this function in document ready:

$(document).ready(function () {
        $.fancybox({
            'width': '40%',
            'height': '40%',
            'autoScale': true,
            'transitionIn': 'fade',
            'transitionOut': 'fade',
            'type': 'iframe',
            'href': 'http://www.example.com'
        });
});

You can put link like this (it will be hidden. May be before </body>)

<a id="clickbanner" href="image.jpg" rel="gallery"></a>

And working rel attribute or class like this

$(document).ready(function() {
    $("a[rel=gallery]").fancybox({
        openEffect  : 'elastic',
        closeEffect : 'elastic',
        maxWidth    : 800,
        maxHeight   : 600
    });
});

Just do it with jquery trigger function

$( window ).load(function() {
  $("#clickbanner").trigger('click');
});

In case if you don't have button to click. I mean if you want to open it on ajax response then it would be like this :

$.fancybox({
      href: '#ID',
      padding   : 23,
      maxWidth  : 690,
      maxHeight : 345
});

Alex's answer is great. but It is importanting to note that that calls the default fancybox style. If you have your own custom rules, you should just call .trigger click on that specific anchor

$(document).ready(function() {
$("#hidden_link").fancybox({ 
    'padding':          0,
    'cyclic':       true,
    'width':        625,
    'height':       350,
    'padding':      0, 
    'margin':      0, 
    'speedIn':      300,
    'speedOut':     300,
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'easingIn':     'swing',
    'easingOut':    'swing',
    'titleShow' : false
}); 
    $("#hidden_link").trigger('click');
});

maybe you can use jqmodal,it's lightweight and easy to use. you can show the modal box by calling

$('.box').jqmShow() 

For my case, the following can work successfully. When the page is loaded, the lightbox is pop-up immediately.

JQuery: 1.4.2

Fancybox: 1.3.1

<body onload="$('#aLink').trigger('click');">
<a id="aLink" href="http://www.google.com" >Link</a></body>

<script type="text/javascript">
    $(document).ready(function() {

        $("#aLink").fancybox({
            'width'             : '75%',
            'height'            : '75%',
            'autoScale'         : false,
            'transitionIn'      : 'none',
            'transitionOut'     : 'none',
            'type'              : 'iframe'
        });
    });
</script>

Maybe this will help... this was used in the full size jQuery calendar click event (http://arshaw.com/fullcalendar/)... but it can be used more generally to deal with fancybox being launched by jQuery.

  eventClick: function(calEvent, jsEvent, view) {
      jQuery("body").after('<a id="link_'+calEvent.url+'" style="display: hidden;" href="http://thisweekinblackness.com/wp-content/uploads/2009/01/steve-urkel.jpg">Steve</a>');
      jQuery('#link_'+calEvent.url).fancybox(); 
      jQuery('#link_'+calEvent.url).click();
      jQuery('#link_'+calEvent.url).remove();
    return false;
  }

I actually managed to trigger a fancyBox link only from an external JS file using the "live" event:

First, add the live click event on your future dynamic anchor:

$('a.pub').live('click', function() {
  $(this).fancybox(... fancybox parameters ...);
})

Then, append the anchor to the body:

$('body').append('<a class="iframe pub" href="your-url.html"></a>');

Then trigger the fancyBox by "clicking" the anchor:

$('a.pub').click();

The fancyBox link is now "almost" ready. Why "almost" ? Because it looks like you need to add some delay before trigger the second click, otherwise the script is not ready.

It's a quick and dirty delay using some animation on our anchor but it works well:

$('a.pub').slideDown('fast', function() {
  $('a.pub').click();
});

Here you go, your fancyBox should appears onload!

HTH


why isn't this one of the answers yet?:

$("#manual2").click(function() {
    $.fancybox([
        'http://farm5.static.flickr.com/4044/4286199901_33844563eb.jpg',
        'http://farm3.static.flickr.com/2687/4220681515_cc4f42d6b9.jpg',
        {
            'href'  : 'http://farm5.static.flickr.com/4005/4213562882_851e92f326.jpg',
            'title' : 'Lorem ipsum dolor sit amet, consectetur adipiscing elit'
        }
    ], {
        'padding'           : 0,
        'transitionIn'      : 'none',
        'transitionOut'     : 'none',
        'type'              : 'image',
        'changeFade'        : 0
    });
});

now just trigger your link!!

got this from the Fancybox homepage


The best way I've found is:

<script type="text/javascript">
    $(document).ready(function() {
        $.fancybox(
             $("#WRAPPER_FOR_hidden_div_with_content_to_show").html(), //fancybox works perfect with hidden divs
             {
                  //fancybox options
             }
        );
    });
</script>

$(document).ready(function() {
    $.fancybox(
      '<p>Yes. It works <p>',
       {
        'autoDimensions'    : false,
        'width'             : 400,
        'height'            : 200,
        'transitionIn'      : 'none',
        'transitionOut'     : 'none'
       }
    );
});

This will help..


HTML:

<a id="hidden_link" href="LinkToImage"></a>

JS:

<script type="text/javascript">
    $(document).ready(function() {
        $("#hidden_link").fancybox().trigger('click');
    });
</script>

You can also use the native JavaScript function setTimeout() to delay the display of the box after the DOM is ready.

<a id="reference-first" href="#reference-first-message">Test the Popup</a>

<div style="display: none;">
    <div id="reference-first-message" style="width:400px;height:100px;overflow:auto;">
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam quis mi eu elit tempor facilisis id et neque. Nulla sit amet sem sapien. Vestibulum imperdiet porta ante ac ornare. Nulla et lorem eu nibh adipiscing ultricies nec at lacus. Cras laoreet ultricies sem, at blandit mi eleifend aliquam. Nunc enim ipsum, vehicula non pretium varius, cursus ac tortor. Vivamus fringilla congue laoreet. Quisque ultrices sodales orci, quis rhoncus justo auctor in. Phasellus dui eros, bibendum eu feugiat ornare, faucibus eu mi. Nunc aliquet tempus sem, id aliquam diam varius ac. Maecenas nisl nunc, molestie vitae eleifend vel, iaculis sed magna. Aenean tempus lacus vitae orci posuere porttitor eget non felis. Donec lectus elit, aliquam nec eleifend sit amet, vestibulum sed nunc.
    </div>
</div>

<script type="text/javascript">
    $(document).ready(function() {
        $("#reference-first").fancybox({
            'titlePosition'         : 'inside',
            'transitionIn'          : 'fade',
            'transitionOut'         : 'fade',
            'overlayColor'          : '#333',
            'overlayOpacity'        : 0.9
        }).trigger("click");

        //launch on load after 5 second delay
        window.setTimeout('$("#reference-first")', 5000);
    });
</script>

Or use this in the JS file after your fancybox is set up:

$('#link_id').trigger('click');

I believe Fancybox 1.2.1 will use default options otherwise from my testing when I needed to do this.


Examples related to jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to jquery-plugins

How to use a jQuery plugin inside Vue How add spaces between Slick carousel item Bootstrap carousel multiple frames at once Can someone explain how to implement the jQuery File Upload plugin? Correct way to integrate jQuery plugins in AngularJS Call Jquery function Twitter bootstrap remote modal shows same content every time Jquery Chosen plugin - dynamically populate list by Ajax How to show all rows by default in JQuery DataTable Change Placeholder Text using jQuery

Examples related to fancybox

Youtube autoplay not working on mobile devices with embedded HTML5 player Fancybox doesn't work with jQuery v1.9.0 [ f.browser is undefined / Cannot read property 'msie' ] Show a div with Fancybox Open fancybox from function Loading inline content using FancyBox Open youtube video in Fancybox jquery jQuery - Fancybox: But I don't want scrollbars! close fancy box from function from within open 'fancybox' Using jQuery Fancybox or Lightbox to display a contact form How to launch jQuery Fancybox on page load?