How to change FancyBox 2 options on the fly?

馋奶兔 提交于 2019-12-02 07:17:52

Unfortunately you cannot change the closeClick behavior of the current fancybox once it has been opened; you could only evaluate a condition within the beforeLoad or afterLoad callbacks and change the API options using jQuery.extend() though.

However, as a workaround, you could simulate the API settings and catch click events on the overlay to decide whether to close fancybox or not for user-initiated changes so

var _closeClick = true; // to simulate overlay closeClick default settings
jQuery(document).ready(function ($) {
    $(".fancybox").fancybox({
        // it's important ro revert default settings so we can catch click events
        helpers: {
            overlay: {
                closeClick: false // default is true
            }
        },
        afterLoad: function () {
            // simulate _closeClick default value
            _closeClick = true;

        },
        // once fancybox is opened, listen for user-initiated changes
        afterShow: function () {
            // button that simulates user-initiated event
            // toggle overlay closeClick on/off on button click
            $("#closeclick").on("click", function (e) {
                _closeClick = _closeClick ? false : true;
                // log changes (debugging)
                var _html = "set overlay closeClick to " + (_closeClick ? false : true) + "";
                $(this).html(_html);
                $("#inline").append("<span id='temp' style='display:block' />");
                $("#temp").html("Current overlay closeClick = " + _closeClick);
                // avoid further click propagation from parent (the overlay perhaps)
                e.stopPropagation();
            });
            // bind a click event to overlay
            $(".fancybox-overlay").on("click", function () {
                // if flag is set to true, close fancybox
                if (_closeClick) {
                    $.fancybox.close();
                };
            });
            $(".fancybox-wrap").on("click", function (event) {
                // stopPropagation on children coming from overlay, including #closeclick
                event.stopPropagation();
            });            
        },
        beforeClose: function () {
            // restore settings
            $("#temp").remove();
            $(".fancybox-overlay, .fancybox-wrap").unbind("click");
        }
    });
}); // ready

See JSFIDDLE

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!