How to launch jQuery Fancybox on page load?
Asked Answered
B

19

97

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.

Bahadur answered 30/4, 2009 at 14:42 Comment(2)
If you go to the official fancybox web site (fancybox.net) they have an automatic popup, so you can check their page source to see how they did it (hint: not the same as the accepted answer)Buhl
To save some time for the others - $(function() { $.fancybox('<div>Change me</div>', {padding: 20}); });Bayern
B
165

Fancybox currently does not directly support a way to automatically launch. The work around I was able to get working is creating a hidden anchor tag and triggering it's click event. Make sure your call to trigger the click event is included after the jQuery and Fancybox JS files are included. The code I used is as follows:

This sample script is embedded directly in the HTML, but it could also be included in a JS file.

<script type="text/javascript">
    $(document).ready(function() {
        $("#hidden_link").fancybox().trigger('click');
    });
</script>
Bahadur answered 4/5, 2009 at 17:37 Comment(4)
just an FYI the $(document).ready(function() { $("#hidden_link").fancybox().trigger('click'); }); is the same as: function LaunchFancyBox() { $("#hidden_link").fancybox().trigger('click'); } $(document).ready(LaunchFancyBox());Stereo
Is the same as $(document).ready(LaunchFancyBox()); should be $(document).ready(LaunchFancyBox);. (note the lack of the function call at the end).Mediatorial
I did try this, but without success. I had to load the content via Ajax then I call $.fancybox({... passing the content.Alded
@Bahadur Your solution $("#hidden_link").fancybox().trigger('click'); works perfect for me.Gook
W
69

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'
        });
});
Wilke answered 6/9, 2010 at 3:14 Comment(5)
This didn't work for me because something goes wrong with handling the href parameter. The "wait" animation shows forever.Thaliathalidomide
It is worth noting that this seems to be the method which the fancybox developers themself. If you head to the fancybox web site (fancybox.net) you should see a modal dialog telling you that "fancybox2 is released!" ... if you look at the source for that page you can see that they have used the technique described in this answer.Buhl
This should be the accepted answer! The accepted solution is working, but adding a hidden anchor over which you trigger a click event is not really the cleanest one, is it?Gelasius
Agreed, using a hidden link is a hack. Do it right.Avina
Very simple! Thanks! I have an autoplay youtube embed in it. Is there any way to close de lightbox as soon the video finishes?Ponytail
L
12

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

Linnie answered 29/3, 2014 at 7:18 Comment(0)
P
10

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().

Primitivism answered 22/8, 2012 at 19:48 Comment(2)
This answer works better for me when I want a page to start with an ios-like warning pop up and then be able to close it. The most popular answer when I tried to implement it made it so ever time I clicked fancybox.close the element would reload instead of go away. Thanks!Parcenary
Your answer sir is most relevant and 100% correct. Thanks.Schoenburg
R
8

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.

Recoverable answered 30/4, 2009 at 14:42 Comment(0)
M
5

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

Maidinwaiting answered 28/2, 2011 at 14:59 Comment(0)
F
5

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>
Foumart answered 30/3, 2011 at 12:55 Comment(1)
This will fail because the closing bracket of the options is commented.Wordless
H
4

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>
Halftimbered answered 16/9, 2010 at 16:17 Comment(0)
R
4

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');
});
Rashad answered 11/11, 2010 at 20:16 Comment(0)
G
2

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

Glossy answered 14/10, 2009 at 10:12 Comment(0)
P
1

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;
  }
Prebo answered 28/11, 2009 at 18:51 Comment(0)
D
1

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>
Deegan answered 9/8, 2011 at 15:56 Comment(0)
Y
1

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
});
Yawp answered 30/3, 2016 at 4:47 Comment(0)
C
1
$(document).ready(function() {
    $.fancybox(
      '<p>Yes. It works <p>',
       {
        'autoDimensions'    : false,
        'width'             : 400,
        'height'            : 200,
        'transitionIn'      : 'none',
        'transitionOut'     : 'none'
       }
    );
});

This will help..

Carola answered 7/10, 2016 at 5:45 Comment(0)
T
1
<script type="text/javascript">
    $(document).ready(function() {
        $('[data-fancybox="gallery"]').click(); 
    });
</script>

easiest solution would be this

Teeth answered 1/11, 2023 at 6:12 Comment(0)
K
0

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');
});
Krissykrista answered 12/3, 2014 at 9:52 Comment(0)
I
0

HTML:

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

JS:

<script type="text/javascript">
    $(document).ready(function() {
        $("#hidden_link").fancybox().trigger('click');
    });
</script>
Isoagglutinin answered 2/8, 2018 at 0:54 Comment(1)
While this code may answer the question, providing additional context regarding how and/or why it solves the problem would improve the answer's long-term value.Permeable
G
0

Using version 3.5.7 of Fancybox I was able to auto-launch it without any extra Javascript. Just add a reference to your Fancybox "group" as an anchor link in the URL.

For example if this is your markup:

<a href="foo.jpg" data-fancybox="gallery">Click me</a>

Just use the following link:

https://example.org/slideshow.php#gallery-1

This automatically opens the slide show for me on page load!

Grampositive answered 28/4, 2021 at 4:34 Comment(0)
M
-1

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

$('.box').jqmShow() 
Memphian answered 30/4, 2009 at 14:52 Comment(2)
I don't think this works because that's not the class of the FancyBoxTanning
My designers want the look and feel of Fancybox, and I would prefer not to go through the effort of trying to implement it for jqmodal. Plus we are already using Fancybox on the site and I don't want to support two different light box impmentations.Bahadur

© 2022 - 2024 — McMap. All rights reserved.