[javascript] Open fancybox from function

I am trying to open a fancybox from a function I have - in short my HTML code looks like this;

<a href="#modalMine" onclick="myfunction(this); return false;">
  click
</a>

and a part of my function looks like this;

function myfunction(me) {
    $(me).fancybox({
        'autoScale': true,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'speedIn': 500,
        'speedOut': 300,
        'autoDimensions': true,
        'centerOnScroll': true,
    });
}

The above works in IE but not in FireFox or Chrome - any idea how I can fix this? I know that one why is to trigger another link, but I hope another solution is possible.

This question is related to javascript jquery fancybox

The answer is


Since you're using jQuery, stop binding event handlers in your HTML, and start writing unobtrusive JavaScript.

$(document).ready(function ()
{
    function myfunction(me)
    {
        $(me).fancybox({
            'autoScale': true,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'speedIn': 500,
            'speedOut': 300,
            'autoDimensions': true,
            'centerOnScroll': true // remove the trailing comma!!
        }).click();
        // fire the click event after initializing fancybox on this element
        // this should open the fancybox
    }

    // use .one() so that the handler is executed at most once per element
    $('a[href=#modalMine]').one('click', function ()
    {
        myfunction(this);
        return false;
    });
});

However, I don't particularly see a reason for setting up the fancybox on click. You could just do this instead:

$(document).ready(function ()
{
    function myfunction()
    {
        // note the use of "this" rather than a function argument
        $(this).fancybox({
            'autoScale': true,
            'transitionIn': 'elastic',
            'transitionOut': 'elastic',
            'speedIn': 500,
            'speedOut': 300,
            'autoDimensions': true,
            'centerOnScroll': true
        });
    }

    $('a[href=#modalMine]').each(myfunction);
});

Basic demo (no images) →


...
<div class="img_file" style="background-image: url('/upload/test/14120330.jpg')" data-img="/upload/test/14120330.jpg"></div>
<div class="img_file" style="background-image: url('/upload/test/14120330.jpg')" data-img="/upload/test/14120330.jpg"></div>
...
if($(".img_file[data-img]").length) {
                var imgs_slider_img = [];
                $(".img_file[data-img]").each(function(i) {
                    imgs_slider_img.push({
                        href:$(this).attr('data-img')
                    });
                    $(this).attr('data-index-img', i);
                }).on("click", function(e) {
                    e.preventDefault();
                    $.fancybox.open(imgs_slider_img, {
                         index: $(this).attr('data-index-img'),
                         padding: 0,
                         margin: 0,
                         prevEffect: 'elastic',
                         nextEffect: 'elastic',
                         maxWidth: '90%',
                         maxHeight: '90%',
                         autoWidth: true,
                         autoHeight: true
                    });
                });
            }
...

You don't have to add you own click event handler at all. Just initialize the element with fancybox:

$(function() {
    $('a[href="#modalMine"]').fancybox({
        'autoScale': true,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'speedIn': 500,
        'speedOut': 300,
        'autoDimensions': true,
        'centerOnScroll': true  // as MattBall already said, remove the comma
    });
});

Done. Fancybox already binds a click handler that opens the box. Have a look at the HowTo section.


Later if you want to open the box programmatically, raise the click event on that element:

$('a[href="#modalMine"]').click();

if jQuery.fancybox.open is not available (on fancybox 1.3.4) you may need to use semafor to get around the recursion problem:

<a href="/index.html" onclick="return myfunction(this)">click me</a>

<script>

var clickSemafor = false;
myfunction(el)
{
 if (!clickSemafor) {
   clickSemafor = true; 
   return false; // do nothing here when in recursion
 }
 var e = jQuery(el); 
 e.fancybox({
    type: 'iframe',
    href: el.href
  }); 
 e.click();  // you could also use e.trigger('click');
 return false; // prevent default

}
</script>

Make argument object extends from <a> , and use open function of fancybox in click event via delegate.

    var paramsFancy={
         'autoScale': true,
         'transitionIn': 'elastic',
         'transitionOut': 'elastic',
         'speedIn': 500,
         'speedOut': 300,
         'autoDimensions': true,
         'centerOnScroll': true,
         'href' : '#contentdiv'
      };

    $(document).delegate('a[href=#modalMine]','click',function(){
               /*Now you can call your function ,
   you can change fields of paramsFancy via this function */
                 myfunction(this);

                paramsFancy.href=$(this).attr('href');
                $.fancybox.open(paramsFancy);

    });

You do not have to trigger a click event, you can do it with fancybox type as ajax.  

$.fancybox.open({
      href: "http://........",
      type: 'ajax'
});

Here is working code as per the author's Tips & Tricks blog post, put it in document ready:

  $("#mybutton").click(function(){
    $(".fancybox").trigger('click');  
  })

This triggers the smaller version of the currently displayed image or content, as if you had clicked on it manually. It avoids initializing the Fancybox again, but instead keeps the parameters you initialized it with on document ready. If you need to do something different when opening the box with a separate button compared to clicking on the box, you will need the parameters, but for many, this will be what they were looking for.


function myfunction(){
    $('.classname').fancybox().trigger('click'); 
}

It works for me..


The answers seems a bit over complicated. I hope I didn't misunderstand the question.

If you simply want to open a fancy box from a click to an "A" tag. Just set your html to

<a id="my_fancybox" href="#contentdiv">click me</a>

The contents of your box will be inside of a div with id "contentdiv" and in your javascript you can initialize fancybox like this:

$('#my_fancybox').fancybox({
    'autoScale': true,
    'transitionIn': 'elastic',
    'transitionOut': 'elastic',
    'speedIn': 500,
    'speedOut': 300,
    'autoDimensions': true,
    'centerOnScroll': true,
});

This will show a fancybox containing "contentdiv" when your anchor tag is clicked.


If you'd like to simply open a fancybox when a javascript function is called. Perhaps in your code flow and not as a result of a click. Here's how you do it:

function openFancybox() {
  $.fancybox({
     'autoScale': true,
     'transitionIn': 'elastic',
     'transitionOut': 'elastic',
     'speedIn': 500,
     'speedOut': 300,
     'autoDimensions': true,
     'centerOnScroll': true,
     'href' : '#contentdiv'
  });
}

This creates the box using "contentdiv" and opens it.


What you need is:

$.fancybox.open({ .... });

See the "API methods" section at the bottom of here:

http://fancyapps.com/fancybox/


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

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 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?