javascriptjqueryfancybox

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.


Solution

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