How to automatically close fancybox/lightbox/... popup after x seconds?

23,866

Solution 1

You can use Fancybox (either version 1.3.x or version 2.x) to open your external html document and close it after some seconds.

For fancybox v1.3.x, your html should look like:

<a href="page.html" class="fancybox">open fancybox and close it automatically after 3 seconds</a>

and the script:

$(document).ready(function() {
 $(".fancybox").fancybox({
  'width': 640, // or whatever
  'height': 320,
  'type': 'iframe',
  'onComplete': function(){
    setTimeout( function() {$.fancybox.close(); },3000); // 3000 = 3 secs
  }
 });
}); // ready

For fancybox v2.x, the html (notice the class):

<a href="page.html" class="fancybox fancybox.iframe">open fancybox and close it automatically after 3 seconds</a>

and the script:

$(document).ready(function() {
 $(".fancybox").fancybox({
  width: 640, // or whatever
  height: 320,
  afterLoad: function(){
   setTimeout( function() {$.fancybox.close(); },3000); // 3000 = 3 secs
  }
 });
}); // ready

Solution 2

onComplete or afterLoad is not working for me, so I have added below code on parent page

window.closeFancyBox = function () {
        $.fancybox.close();
};

and from popup page I am calling below code

$(window).load(function(){ setTimeout( function() {window.parent.closeFancyBox(); },3000); // 3000 = 3 secs });

Share:
23,866
zigamilek
Author by

zigamilek

Updated on July 29, 2020

Comments

  • zigamilek
    zigamilek almost 4 years

    I have a test website (index.html) that opens a popup (popup.html) and closes it after three seconds. Here's the head of index.html:

    <script language="javascript" type="text/javascript">
    function popup(url) {
        newwindow=window.open(url,'name','height=70,width=300');
        if (window.focus) {newwindow.focus()}
        return false;
    }
    </script>
    

    Here's the body of index.html:

    <a href="#" onClick="return popup('popup.html')">Open in pop-up</a>
    

    Here's the head of popup.html:

    <script>
        var howLong = 3000;
        t = null;
        function closeMe(){
            t = setTimeout("self.close()",howLong);
        }
    </script>
    

    Here's the body of popup.html:

    <body onLoad="closeMe();self.focus()">
    <p>Closing in 3 seconds</p>
    </body>
    

    I'd like to show that popup using linghtbox/fancybox/whatever... and again close it after 3 seconds. How can I do that? I tried all sorts of things and nothing worked. What's the easiest way to implement this?

    Thanks in advance!