31

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.

pythonian29033
  • 5,148
  • 5
  • 31
  • 56
keysersoze
  • 777
  • 3
  • 12
  • 27

11 Answers11

40

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.

Daniel
  • 1,531
  • 13
  • 16
27

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) →

Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • 3
    This doesn't look right. I don't know how fancybox handles it, but this initializes fancybox on each click anew. – Felix Kling Feb 23 '11 at 17:33
  • @Felix: yeah, I've never used fancybox before - I was only looking at the OP's code. – Matt Ball Feb 23 '11 at 17:56
  • First of all I am sorry for my typo - it was because it was only a part of a bigger code. Next, the above do not work unless I click twice at my link. – keysersoze Feb 25 '11 at 13:16
  • @keysersoze: as Felix points out in his answer, this is because fancybox adds its own click handler, which is what needs to be fired for the fancybox to show. – Matt Ball Feb 25 '11 at 14:04
  • while you have been making your suggestion I got it fixed also with the following code `$(document).ready(function () { myfunction(this, null, ....); $('.link').each(function () { myfunction(this, 'dosomething(' + this.id + ');', ....);'); }); });` so thank you very much for your help :) – keysersoze Feb 25 '11 at 15:54
  • @Matt Ball in JavaScript opening curly braces should always go on the same line as the expression, as opposed to on the next line down like in other languages such as c# – danwellman Sep 14 '12 at 09:05
  • @danwellman let me guess: you're saying that because of semicolon insertion when returning an object literal, right? Well, I must respectfully disagree with you. I prefer Allman-style braces; in turn, I don't try to directly return object literals, or if I do, I make an exception in my indentation then and then only. – Matt Ball Sep 14 '12 at 10:54
  • @Matt Ball yes, but it's nothing to do with indentation. Best-practices are best-practices for a reason. Besides that I just think it looks terrible ;) – danwellman Sep 14 '12 at 11:40
  • @danwellman so where is this specific best practice defined? In every non-whitespace-sensitive language with C-style braces, I've always seen it to be a subjective choice. Also, I don't see how it has "nothing to do with indentation." – Matt Ball Sep 14 '12 at 13:23
  • @Matt Ball, this specific best practice is defined in one of the JavaScript bibles - *JavaScript - the good parts* by Douglas Crockford. It's also implied here: http://javascript.crockford.com/code.html but not really covered in detail. It *is* a best-practice, whether you adhere to it or not, and it has nothing to do with indentation because the indentation happens *on the next line down* and has no bearing on the brace in question. A different form of indentation will not rescue you from ASI – danwellman Sep 14 '12 at 18:57
  • great example..thanks! I have a question though.. how can i close the dialog ? clicking on close icon doesn't work in the given fiddle. – Hiral Vadodaria May 09 '16 at 09:01
18

What you need is:

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

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

http://fancyapps.com/fancybox/

Adrian Smith
  • 17,236
  • 11
  • 71
  • 93
  • But Fancybox2 works, unlike 1.3.4 which is bug ridden. I wasted 3 on version 1 bugs with a rails 3.2 app today, when I could have invested $19 for Fancybox2 initially. – jpw Dec 20 '13 at 07:05
8

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();
Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 1
    The reason why I do not do as you suggest and the fancybox doc also write is, that I need more functionality to run than just open the fancybox - my method needs 6 parameters to handle e.g. the title of the window, which formfield needs focus and complete + close code. each button on my page uses the same window but each button also have indiviual actions to do when working in the fancybox. So, if my function looks like this `function initModal(target, titletarget, titlestring, focus, completecode, closecode)` how should I then use it on my different buttons? – keysersoze Feb 25 '11 at 13:25
5

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

$.fancybox.open({
      href: "http://........",
      type: 'ajax'
});
frzsombor
  • 2,274
  • 1
  • 22
  • 40
Burcu Co
  • 83
  • 2
  • 6
3

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);

    });
Abdennour TOUMI
  • 87,526
  • 38
  • 249
  • 254
2

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.

Henrik Erlandsson
  • 3,797
  • 5
  • 43
  • 63
2
function myfunction(){
    $('.classname').fancybox().trigger('click'); 
}

It works for me..

Prabhagaran
  • 3,620
  • 1
  • 19
  • 19
2

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.

Daniel
  • 1,531
  • 13
  • 16
1
...
<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
                    });
                });
            }
...
  • Please provide more information with your code, not just a code sample. Explain what you did and why this answers the question. – MechMK1 Nov 23 '17 at 14:39
0

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>
stAn
  • 21
  • 4