PageSourceSearch

https://xn--400-eddplucwdhb0e2b.xn--p1ai/plugins/newmodal/newmodal.js

js xn--400-eddplucwdhb0e2b.xn--p1ai collected 2026-10-02 11:48:40 UTC 15,618 bytes, 299 lines download raw bytes

1(function($) {
2    $.fn.modal = function(method){
3        var $this = this;
4        var options = {
5            "closeBefore":function(){return true;},
6            "closeAfter":function(){return true;},
7            "openAfter":function(){return true;},
8            "openBefore":function(){return true;},
9            "defaultMargin":100,
10            "defaultWidth":500,
11            "animateTime":400
12        }
13        function getScrollBarWidth(){
14            var div = document.createElement('div');
15            div.style.overflowY = 'scroll';
16            div.style.width =  '50px';
17            div.style.height = '50px';
18
19            // при display:none размеры нельзя узнать
20            // нужно, чтобы элемент был видим,
21            // visibility:hidden - можно, т.к. сохраняет геометрию
22            div.style.visibility = 'hidden';
23
24            document.body.appendChild(div);
25            var scrollWidth = div.offsetWidth - div.clientWidth;
26            document.body.removeChild(div);
27            return scrollWidth;
28        }
29        function refreshModal(html, modalItem, resize){
30            resize = resize || false;
31            var modal_container = $("#modal_container");
32            var newModal = $(".popup_inblock", modalItem);
33            var fade = $(".fade_modal", modalItem);
34            fade.css({"height": 0, "width": 0});
35            if(resize){
36                html.removeAttr("style");
37                var htmlWidth = html.width();
38                var styleHtml = {/*"height": htmlHeight +"px", "margin-top": 0-window.pageYOffset+"px",*/ "overflow": "hidden", "min-height": "100%", "min-width": htmlWidth+"px", "width": htmlWidth+"px"};
39                html.css(styleHtml);
40
41                var topMarginModal = Math.round((modal_container.height() - newModal.height())/2);
42                var defaultMargin = options.defaultMargin;
43                if(topMarginModal < defaultMargin ){
44                    topMarginModal = defaultMargin;
45                }
46                newModal.css({"margin-top":topMarginModal + "px"});
47            }
48            fade.css({"height": modalItem[0].scrollHeight + "px", "width": modalItem[0].scrollWidth + "px"});
49        }
50        function open(element){
51            if(element.length < 1)return;
52            if($(".modal_item[name='"+element.attr("id")+"']").length > 0)return;
53            //некоторый значения по умолчанию
54            var defaultMargin = options.defaultMargin;
55            var defaultWidth = options.defaultWidth;
56            //поместим в контейнер все что внутри модалки
57            //структура след: контейнер в нем итем в итеме внутренности модалки в обертке, тень и блок для нижнего отступа модалки
58            //при открытии модалки все время добавляется итем
59
60            //контейнер
61            var modal_container;
62            if($("#modal_container").length==0){
63                modal_container = $('<div/>', {"id": 'modal_container'});
64                $("body").append(modal_container);
65            }else{
66                modal_container = $("#modal_container");
67            }
68            //создание итема
69            var modalItem = $('<div/>', {"data-id": element.attr("id"),"name": element.attr("id"),"class": "modal_item"});
70           modal_container.append(modalItem);
71           var newModal = $('<div/>', {"class": "popup_inblock"+" "+element.attr("class")});
72           //вставим закрывающий крестик
73           var closeBtn = $('<div/>',{"class": "close","title":"Закрыть"});
74           newModal.append(closeBtn);
75           //вешаем обработчик
76           closeBtn.click(function(){
77               close(element);
78               return false;
79           });
80           modalItem.append(newModal);
81           var modal = element[0];
82           while(modal.firstChild) {
83                //elem.cloneNode(true)
84                newModal.append(modal.firstChild);
85           }
86
87           //рассчет высоты обертки модалки
88           var modalHeight = newModal.height() + defaultMargin;
89           modalHeight = Math.max(window.innerHeight, modalHeight); // не может быть меньше окна
90
91           //спозиционировать модалку внутри итема
92           //лево всегда -половина ширины
93           var modalWidth = element.attr("data-width") || defaultWidth;
94           
95           var modalPaddingWidth = modalWidth * 1 + modalItem.find(".popup_inblock").css("padding-left").replace("px", "") * 1 + modalItem.find(".popup_inblock").css("padding-right").replace("px", "") * 1;
96           
97           var leftMarginModal = 0 - Math.round(modalPaddingWidth/2);
98           newModal.css({"width":modalWidth+"px", "margin-left":leftMarginModal + "px"});
99
100           //отступ сверху либо половина либо дефолтное значение
101           var topMarginModal = Math.round((modal_container.height() - newModal.height() - modalItem.find(".popup_inblock").css("padding-top").replace("px", "") * 1 - modalItem.find(".popup_inblock").css("padding-bottom").replace("px", "") * 1)/2);
102           if(topMarginModal < defaultMargin ){
103               topMarginModal = defaultMargin;
104           }
105           newModal.css({"margin-top":topMarginModal + "px"});
106
107           //отступ снизу
108           var shiftItem = $('<div/>', {"class": "shift_item"});
109           modalItem.append(shiftItem);
110
111           //вставим фаде
112           var fade = $('<div/>', {"class": "fade_modal"});
113           modalItem.append(fade);
114           /*if(modalItem.height()<window.innerHeight){
115               modalItem.css("height", window.innerHeight+"px");
116           }*/
117           //повесим обработчик на фаде
118           fade.click(function(){
119               close(element);
120           });
121           //косяк с фаде присвоим ему высоту всей высоты прокрутки
122           fade.css({"height": modalItem[0].scrollHeight + "px", "width": modalItem[0].scrollWidth + "px"});
123           //анимация
124           modalItem.css({"opacity":"0"}).stop(true,false).animate({"opacity":"1"}, options.animateTime,function(){options.openBefore();});
125           //смотрим если контейнер видимый значит надо заблокировать предпоследний элемент (последний это уже новая модалка)
126           //если скрытый то отображаем и работаем с другими элементами
127           if(modal_container.css("display") == "block" && modal_container.css("visibility") == "visible"){
128               //получим предпоследний итем
129               var last_by_one = modal_container.children().last().prev();
130               last_by_one.css({/*"margin-top":0-window.pageYOffset+"px",*/ "position": "fixed"});
131               //window.scrollTo(0, 0);
132           }else{
133               modal_container.css({"visibility":"visible","display":"block", "margin-top": window.pageYOffset+"px"});
134               //блокируем страницу
135               var html = $("body");
136               /*var htmlHeight = modalHeight + window.pageYOffset;
137               htmlHeight = Math.min(htmlHeight, document.body.scrollHeight);*/
138
139               var htmlWidth = html.width();
140               var styleHtml = {/*"height": htmlHeight +"px", "margin-top": 0-window.pageYOffset+"px",*/ "overflow": "hidden", "min-height": "100%", "min-width": htmlWidth+"px", "width": htmlWidth+"px"};
141               html.css(styleHtml);
142               document.body.onresize = function(){
143                   refreshModal(html, modalItem, true);
144               }
145               //window.scrollTo(0, 0);
146           }
147        }
148        function close(element){
149            if(options.closeAfter(element[0])){
150                var modal_container = $("#modal_container");
151                var modal_item = $("div[name='"+element.attr("id")+"']");
152                if(modal_item.length>0){
153                    //анимация
154                    modal_item.stop(true,false).animate({"opacity":"0"}, options.animateTime, function(){
155                       //удалим крестик
156                       var thisItem = $(this);
157                       thisItem.children(".popup_inblock").children(".close").remove();
158                       var oldModal = thisItem.children(".popup_inblock")[0];
159
160                       while(oldModal.firstChild) {
161                           element.append(oldModal.firstChild);
162                       }
163
164                       thisItem.remove();
165                       //если модалок больше нет разблокируем окно
166                       if(modal_container.children().length == 0){
167                        modal_container.removeAttr("style");
168                        //разблокируем страницу
169                        var html = $("body");
170                        //var scrollY = window.pageYOffset;//0 - parseInt(html.css("margin-top"));
171                        html.removeAttr("style");
172                        document.body.onresize = null;
173                       }else{
174                        //надо разблокировать последний элемент
175                        var lastItem = modal_container.children().last();
176                        //var scrollY = 0 - parseInt(lastItem.css("margin-top"));
177                        lastItem.css({"position":"","margin-top":""});
178                       }
179
180                       //косяк какой-то страница прокручивается вверх :(
181                       //window.scrollTo(0, scrollY);
182                       options.closeBefore(element[0]);
183                    });
184                }
185
186            }
187        }
188        var methods = {
189            "init":function(settings){
190                settings = settings || {};
191                options = $.extend(options, settings);
192                $this.live({
193                    "click":function(){
194                        var modalId = $(this).attr('rel') || $(this).attr('data-modal');
195                        var modal = $("#"+modalId);
196                        if(options.openAfter(modal[0])){
197                            if(!modal.attr("data-width") && $(this).attr('href')){
198                                var width_modal = $(this).attr('href').split('?')[1].split('&')[0].split('=')[1];
199                                modal.attr("data-width", width_modal);
200                            }
201                            open(modal);
202                        }
203                        return false;
204                    }
205                });
206            },
207            "open":function(settings){
208                settings = settings || {};
209                options = $.extend(options, settings);
210                if(options.openAfter($this[0])){
211                    if(!$this.attr("data-width")){
212                        var el = $("[rel='"+$this[0].id+"']");
213                        if(el.length == 0){
214                             el = $("[data-modal='"+$this[0].id+"']");
215                        }
216                        if(el.length > 0 && el.attr('href')){
217                            var width_modal = el.attr('href').split('?')[1].split('&')[0].split('=')[1];
218                            $this.attr("data-width", width_modal);
219                        }
220                    }
221                    open($this);
222                }
223            },
224            "close":function(method, settings){
225                method = method || false;
226                if(typeof method != "string"){
227                    settings = method;
228                }
229                settings = settings || {};
230                options = $.extend(options, settings);
231                if(method == "all"){
232                    $("#modal_container .modal_item").each(function(){
233                        var element = $("#"+$(this).attr("name"));
234                        close(element);
235                    });
236                }else if(method == "last"){
237                    var element = $("#"+$("#modal_container .modal_item:last").attr("name"));
238                    close(element);
239                }else{
240                    close($this);
241                }
242
243            },
244            "destroy":function(settings){
245                settings = settings || {};
246                options = $.extend(options, settings);
247                options["closeBefore"] = function(el){$(el).remove();};
248                close($this);
249            },
250            "refresh":function(){
251                var modalItem = $("[name='"+$this[0].id+"']", $("#modal_container"));
252                if (modalItem.length > 0)
253                    refreshModal($("body"), modalItem);
254            },
255            "fixed": function(settings){
256                var modalItem = $("#modal_container .modal_item:last");
257                
258                if (settings){
259                    if (modalItem.length > 0){
260                        var html = $("body");
261                       $("#modal_container .fade_modal").css("display", "block");
262                       $("#modal_container .modal_item").css("overflow-y", "scroll");
263                       
264                        var htmlWidth = html.width();
265                       var styleHtml = {/*"height": htmlHeight +"px", "margin-top": 0-window.pageYOffset+"px",*/ "overflow": "hidden", "min-height": "100%", "min-width": htmlWidth+"px", "width": htmlWidth+"px"};
266                       html.css(styleHtml);
267                       //$("#modal_container").css({"margin-top": window.pageYOffset+"px"});
268                       $("html,body").animate({"scrollTop": $("#modal_container").css("margin-top")},0);
269                       document.body.onresize = function(){
270                           refreshModal(html, modalItem, true);
271                       }
272                    }
273                   
274                } else {
275                    if (modalItem.length > 0){
276                        $("#modal_container .modal_item").css("overflow-y", "visible");
277                        $("#modal_container .fade_modal").css("display", "none");
278                        $("body").removeAttr("style");
279                        document.body.onresize = null;
280                    }
281                }
282                
283            }
284        };
285        if ( methods[method] ) {
286          // если запрашиваемый метод существует, мы его вызываем
287          // все параметры, кроме имени метода прийдут в метод
288          // this так же перекочует в метод
289          return methods[ method ].apply( this, Array.prototype.slice.call( arguments, 1 ));
290        } else if ( typeof method === 'object' || ! method ) {
291          // если первым параметром идет объект, либо совсем пусто
292          // выполняем метод init
293          return methods.init.apply( this, arguments );
294        } else {
295          // если ничего не получилось
296          $.error( 'Метод "' +  method + '" не найден' );
297        }
298    }
299})(jQuery);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.