Модальное окно на magnific popup со своей анимацией

Inline Type

To create popup from inline element you need to:

1) Create a HTML element that you wish to display in popup and add it somewhere. Class is required to hide the popup from the page.

2) Style this element. Magnific Popup by default doesn’t apply any styles to it, except vertical centering (if ). Close button will be automatically appended inside (if ).

3) Add button that will open the popup (source must match CSS id of an element ( in our case).

4) Initialize script.

Here are some other ways to initialize popup:

I have created two examples on CodePen that will help you better understand how it works:

  • Simple inline popup
  • Advanced popup with markup and gallery mode

Окно приглашения

Поле приглашения часто используется, если пользователь должен ввести значение перед вводом страницы.

Когда появится окно приглашения, пользователь должен будет нажать кнопку «ОК» или «Отмена», чтобы продолжить ввод значения.

Если пользователь нажимает кнопку «ОК», поле Возвращает входное значение. Если пользователь нажимает кнопку «Отмена», поле возвращает значение null.

window.prompt(«sometext«,»defaultText«);

Метод Window. Prompt () можно записать без префикса окна.

Пример

var person = prompt(«Please enter your name», «Harry Potter»);if
(person == null || person == «») {    txt = «User cancelled
the prompt.»;} else {    txt = «Hello » + person + «!
How are you today?»;}

Gallery

The gallery module allows you to switch the content of the popup and adds navigation arrows. It can switch and mix any types of content, not just images. Gallery options:

Example:

Multiple galleries

To have multiple galleries on a page, you need to create a new instance of Magnific Popup for each separate gallery. For example

You don’t necessarily need to use option, it can be just .

Lazy-loading

Lazy-loading option preloads nearby items. It accepts an array with two integers. The first is the number of items to preload before the current. The second is the number of images to preload after the current. For example, will load 3 next items and 1 that is before current. These values are automatically switched based on direction of movement.

By default all what it does is just searches for an image tag and preloads it with JavaScript. But you can extend it and do your custom preloading logic with help of event, like so:

“Preload” option can be changed dynamically. To disable it set .

Examples

Single image lightbox

Three simple popups with different scaling settings.
1 — fits horizontally and vertically,
2 — only horizontally,
3 — no gaps, zoom animation, close icon in top-right corner.

Lightbox gallery

You may put any HTML content in each gallery item and mix content types. In this example lazy-loading of images is enabled for the next image based on move direction. If you wish to add touch-swipe support, check my article on the Smashing Magazine, or new PhotoSwipe script.

Zoom-gallery

If you wish to open the popup only after image is fully loaded, you may preload image via JS. Or use scaled down image instead of thumbnail. Zoom effect works only with images, for now.

Popup with video or map

In this example lightboxes are automatically disabled on small screen size and default behavior of link is triggered.

Open YouTube videoOpen Vimeo videoOpen Google Map

Dialog with CSS animation

Animations are added with simple CSS transitions, you can make them look however you wish.More animation effects on CodePen.

Dialog example

This is dummy copy. It is not meant to be read. It has been placed here solely to demonstrate the look and feel of finished, typeset text. Only for show. He who searches for meaning here will be sorely disappointed.

Ajax popup

You have full control of what is displayed in popup, align it to any side via CSS, enable or disable scroll on right side of window — whatever.

Load content via ajaxLoad another content via ajax

Modal popup

A modal popup disables the usual ways to close popups.

Modal dialog

You won’t be able to dismiss this by usual means (escape or
click button), but you can close it programatically based on
user choices or actions.

Error handling

This is just basic example of how error messages are displayed. Surely, you can change text or style them.

Broken imageBroken ajax request

Don’t forget to check out my new article about this plugin on the Smashing Magazine.

Initializing popup

Popup initialization code should be executed after document ready, for example:

There are three ways to initialize a popup:

2. From a group of elements with one parent

Same as first one, but use this method if you are creating a popup from a list of elements in one container. Note that this method does not enable gallery mode, it just reduces the number of click event handlers; each item will be opened as a single popup. If you wish to enable gallery, add the option.

3. From the ‘items’ option

The option defines data for the popup item(s) and makes Magnific Popup ignore all attributes on the target DOM element. The value for can be a single object or an array of objects.

Play with this example on CodePen.

Как использовать

Рассмотрим как использовать Magnific popup с анимацией на примере зума. Для этого потребуется:

1. Задать css стили для самого модального окна и для выбранной анимации.

style.css

.white-popup {
position: relative;
background: #FFF;
padding: 25px;
max-width: 400px;
margin: 0 auto; }

1
2
3
4
5
6

.white-popup{

positionrelative;

background#FFF;

padding25px;

max-width400px;

marginauto;}

Стили для анимации зума:

/* ZOOM */

.mfp-zoom-in .mfp-with-anim {
opacity: 0;
-webkit-transition: all 0.2s ease-in-out;
-o-transition: all 0.2s ease-in-out;
transition: all 0.2s ease-in-out;
-webkit-transform: scale(0.8);
-ms-transform: scale(0.8);
transform: scale(0.8); }

.mfp-zoom-in.mfp-bg {
opacity: 0;
-webkit-transition: all 0.3s ease-out;
-o-transition: all 0.3s ease-out;
transition: all 0.3s ease-out; }

.mfp-zoom-in.mfp-ready .mfp-with-anim {
opacity: 1;
-webkit-transform: scale(1);
-ms-transform: scale(1);
transform: scale(1); }

.mfp-zoom-in.mfp-ready.mfp-bg {
opacity: 0.8; }

.mfp-zoom-in.mfp-removing .mfp-with-anim {
-webkit-transform: scale(0.8);
-ms-transform: scale(0.8);
transform: scale(0.8);
opacity: 0; }

.mfp-zoom-in.mfp-removing.mfp-bg {
opacity: 0; }

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

/* ZOOM */
 

.mfp-zoom-in.mfp-with-anim{

opacity;

-webkit-transitionall0.2sease-in-out;

-o-transitionall0.2sease-in-out;

transitionall0.2sease-in-out;

-webkit-transformscale(0.8);

-ms-transformscale(0.8);

transformscale(0.8);}

.mfp-zoom-in.mfp-bg{

opacity;

-webkit-transitionall0.3sease-out;

-o-transitionall0.3sease-out;

transitionall0.3sease-out;}

.mfp-zoom-in.mfp-ready.mfp-with-anim{

opacity1;

-webkit-transformscale(1);

-ms-transformscale(1);

transformscale(1);}

.mfp-zoom-in.mfp-ready.mfp-bg{

opacity0.8;}

.mfp-zoom-in.mfp-removing.mfp-with-anim{

-webkit-transformscale(0.8);

-ms-transformscale(0.8);

transformscale(0.8);

opacity;}

.mfp-zoom-in.mfp-removing.mfp-bg{

opacity;}

2. Добавить блок модального окна в html (для удобства в конец

index.html

Zoom popup

Lorem ipsum, dolor sit amet consectetur adipisicing elit. Deleniti itaque ipsam illum eaque, odio cumque quam asperiores dolores labore ab.

1
2
3
4
5

div id=»test-popup»class=»white-popup mfp-with-anim mfp-hide»>

h2>Zoom popuph2>

img src=»http://webgrind.ru/wp-content/uploads/2018/09/cat.jpg»alt=»»>

p>Lorem ipsum,dolor sit amet consectetur adipisicing elit.Deleniti itaque ipsam illum eaque,odio cumque quam asperiores dolores labore ab.p>

div>

Где в id вы указываете уникальное имя попапа. Т.е если вам нужно 2 разных, то добавляете 2 блока с разными id и каждый вызываете со своим значением href. В data-effect указываем необходимый тип анимации. Для зума это «mfp-zoom-in».

1
2
3
4

ul>

li>ahref=»#test-popup»class=»show-popup»data-effect=»mfp-zoom-in»>Зумa>li>

li>ahref=»#another-popup»class=»show-popup»data-effect=»mfp-zoom-in»>Газетаa>li>

ul>

3. Добавить в js вызов попапа. Где «show-popup» — класс объекта по которому вызывается какой-либо попап. Также в 6 строке  указывается откуда будет считываться выбранный тип анимации.

common.js

$(‘.show-popup’).magnificPopup({
type: ‘inline’,
removalDelay: 500, //delay removal by X to allow out-animation
callbacks: {
beforeOpen: function () {
this.st.mainClass = this.st.el.attr(‘data-effect’);
}
},
midClick: true // allow opening popup on middle mouse click. Always set it to true if you don’t provide alternative source.
});

1
2
3
4
5
6
7
8
9
10

$(‘.show-popup’).magnificPopup({

type’inline’,

removalDelay500,//delay removal by X to allow out-animation

callbacks{

beforeOpenfunction(){

this.st.mainClass=this.st.el.attr(‘data-effect’);

}

},

midClicktrue// allow opening popup on middle mouse click. Always set it to true if you don’t provide alternative source.

});

What makes this plugin different?

Light and modular

You can choose to include only the features that you need using the or by compiling it yourself with Grunt.js. Size of core JS file is about 3KB + each module weighs about 0.5KB (gzipped). Sass CSS preprocessor is used for easier skinning, but you’re not obligated to use it.

Content is resized with CSS

The majority of lightbox plugins require you to define size of it via JS option. Magnific Popup does not — feel free to use relative units like EM’s or resize lightbox with help of CSS media queries. Update content inside lightbox without worrying about how it’ll resize and center.

Fast

Magnific Popup displays images before they’re completely loaded to take full advantage of progressive loading. For in and out transitions CSS3 is used instead of slow JavaScript animation.

High-DPI (Retina) display support

Default controls are made with pure CSS, without external graphics. For the main image there is a built in way to provide appropriate source for different pixel density displays.

Conditional lightbox

Plugin has an option to automatically switch to alternative mobile-friendly source on small screen size. Brad Frost has a terrific article about this technique.

Memory management

Popup has an extendable micro templating engine that reuses existing DOM elements (example), which is especially useful when your popups same pattern.

Content Types

By default, Magnific Popup has four types of content: , , , and . There is no any “auto-detection” of type based on URL, so you should define it manually.

The type of a popup can be defined in a two ways:

  1. Using the option. E.g.: .

  2. Using the CSS class (where is the desired content type). For example: , .

The second option always overrides the first, so you may initialize popups with multiple content types from one call.

is the default content type (from v0.8.4), so you may skip its definition.

The source of the the popup content (for example, a path to an image, a path to an HTML file, a path to a video page) can be defined in a few ways:

Method #1: From the attribute:

Method #2: From the attribute (overrides the first method):

Method #3: From the option

If you want to modify how the source is parsed, you may hook into the callback. For example:

JS Уроки

JS HOMEJS IntroductionJS Where ToJS OutputJS StatementsJS SyntaxJS CommentsJS VariablesJS OperatorsJS ArithmeticJS AssignmentJS Data TypesJS FunctionsJS ObjectsJS ScopeJS EventsJS StringsJS String MethodsJS NumbersJS Number MethodsJS ArraysJS Array MethodsJS Array SortJS Array IterationJS DatesJS Date FormatsJS Date Get MethodsJS Date Set MethodsJS MathJS RandomJS BooleansJS ComparisonsJS ConditionsJS SwitchJS Loop ForJS Loop WhileJS BreakJS Type ConversionJS BitwiseJS RegExpJS ErrorsJS DebuggingJS HoistingJS Strict ModeJS this KeywordJS Style GuideJS Best PracticesJS MistakesJS PerformanceJS Reserved WordsJS VersionsJS Version ES5JS Version ES6JS JSON

API

There is a much bigger list of public events, methods and variables than provided here which is used for module development, look inside code or type in console to find them, if you think that something should be added to docs — please submit commit.

Events

You can define callbacks in option. Besides that, all Magnific Popup events are also dispatched using on target element (or to document if the element doesn’t exist).

List of callbacks. In each callback is , so you can execute methods () or access public variables ().

Public methods

You may also call ANY method via after you initialized the popup, for example:

You may also open the popup directly at initialization:

JS Tutorial

JS HOMEJS IntroductionJS Where ToJS OutputJS StatementsJS SyntaxJS CommentsJS VariablesJS OperatorsJS ArithmeticJS AssignmentJS Data TypesJS FunctionsJS ObjectsJS EventsJS StringsJS String MethodsJS NumbersJS Number MethodsJS ArraysJS Array MethodsJS Array SortJS Array IterationJS DatesJS Date FormatsJS Date Get MethodsJS Date Set MethodsJS MathJS RandomJS BooleansJS ComparisonsJS ConditionsJS SwitchJS Loop ForJS Loop WhileJS BreakJS Type ConversionJS BitwiseJS RegExpJS ErrorsJS ScopeJS HoistingJS Strict ModeJS this KeywordJS LetJS ConstJS Arrow FunctionJS ClassesJS DebuggingJS Style GuideJS Best PracticesJS MistakesJS PerformanceJS Reserved WordsJS VersionsJS Version ES5JS Version ES6JS JSON

Options

Options should be passed to the initialization code and separated by comma, e.g.:

Options for specific modules are explained in their sections of documentation (e.g. related to text are in , related to gallery are in . Here you can find the list of general options:

disableOn

If window width is less than the number in this option lightbox will not be opened and the default behavior of the element will be triggered. Set to to disable behavior. Option works only when you initialize Magnific Popup from DOM element.

Can also accept Function as a parameter, which should return if lightbox can be opened and otherwise. For example:

key

“Key” option is a unique identifier of a single or a group of popups with the same structure. If you will not define it, DOM elements will be created and destroyed each time when you open and close popup.

You may (and should) set an equal key to different popups if their markup matches. By markup I mean options that change HTML structure of the popup (e.g. close icon placement and HTML code of it).

For example: you have many popups that show title, some text and button — you may use one key for all of them, so only one instance of this element is created. Same for popup that always contains image and caption.

You can delete cached templates like so:

midClick

If set to lightbox is opened if the user clicked on the middle mouse button, or click with Command/Ctrl key. Option works only when you initialize Magnific Popup from DOM element.

mainClass

String that contains classes that will be added to the root element of popup wrapper and to dark overlay. For example , can also contain multiple classes — .

preloader

Preloader in Magnific Popup is used as an indicator of current status. If option enabled, it’s always present in DOM only text inside of it changes. Below you can see explanation of CSS names that are applied to container that holds preloader and content area depending on the state of current item:

For example, if you want your error message to be in red add such CSS:

You can trigger change of status manually by calling .

focus

String with CSS selector of an element inside popup that should be focused. Ideally it should be the first element of popup that can be focused. For example or . Leave empty to focus the popup itself.

closeBtnInside

If enabled, Magnific Popup will put close button inside content of popup, and wrapper will get class (which in default CSS file makes color of it change). If markup of popup item is defined element with class it will be replaced with this button, otherwise close button will be appended directly.

modal

When set to , the popup will have a modal-like behavior: it won’t be
possible to dismiss it by usual means (close button, escape key, or
clicking in the overlay).

This is a shortcut to set , ,
, and to .

alignTop

If set to popup is aligned to top instead of to center. (basically all this option does is adds CSS class to popup which removes styles that align popup to center).

fixedContentPos

Popup content position. Can be , or . If set to — fixed position will be used, to — absolute position based on current scroll. If set to popup will automatically disable this option when browser doesn’t support fixed position properly.

fixedBgPos

Same as an option above, but it defines position property of the dark transluscent overlay. If set to — huge tall overlay will be generated that equals height of window to emulate fixed position. It’s recommended to set this option to if you animate this dark overlay and content is most likely will not be zoomed, as size of it will be much smaller.

overflowY

Defines scrollbar of the popup, works as overflow-y CSS property — any CSS acceptable value is allowed (e.g. , , ). Option is applied only when fixed position is enabled.

There is no option , but you may easily emulate it just via CSS.

prependTo

The DOM element to which popup will be added. Useful when you’re using ASP.NET where popup should be inside . Option available since 2013/12/04.

autoFocusLast

If set to last focused element before popup showup will be focused after popup close. Option available since 2015/12/16.

Prompt Box

A prompt box is often used if you want the user to input a value before entering a page.

When a prompt box pops up, the user will have to click either «OK» or «Cancel»
to proceed after entering an input value.

If the user clicks «OK» the box returns the input value. If the user clicks «Cancel» the box returns null.

window.prompt(«sometext«,»defaultText«);

The method can be written without the window prefix.

Example

var person = prompt(«Please enter your name», «Harry Potter»);if
(person == null || person == «») {  txt = «User cancelled
the prompt.»;} else {  txt = «Hello » + person + «!
How are you today?»;}

Инструкция по работе с модулем JT Popup.

Установка модуля самая обычная, через менеджер расширений Joomla. После установки модуль появиться в списке установленных модулей.

Настройки отображения модуля

Режим работы — выбирается режим работы модуля. Открытие с задержкой или по клику.

Запоминать браузером — включить установку куки в браузер, чтобы показывать окно через определённый промежуток времени.

На сколько запоминать — время жизни куки в секундах. 86400 секунд — это 24 часа.

Задержка — задержка показа popup окна в секундах. Рекомендую устанавливать значение более 10 секунд.

ID окна — задаётся ID для окна, если включен режим открытие по клику.

Ширина и высота окна — задаются размеры в пикселях, em или процентах. Работает для окон при просмотре на обычных экранах. На мобильных устройствах модальное окно становиться адаптивным.

Стиль окна — выбирается стиль, тут на вкус и цвет) 

О том как изменить стиль под свой проект смотрите ниже.

Добавление содержимого во всплывающее окно

В модуле существует 3 варианта добавления контента.

  1. Через окно «HTML и JS код» — при этом код не обрезается редактором
  2. Через стандартный редактор Joomla, кому то удобнее через него.
  3. Вставка другого модуля.

Про вставку через модульную позицию расскажу по-подробнее.

В модуле есть опция — добавить позицию. После её включения во всплывающее окно будет добавлена новая позиция с тем именем что вы укажете в поле ниже.

Таким образом вы можете вставить в модальное окно любой модуль. Например, модуль входа на сайт, модуль формы заявки, формы подписки и т.д.

Прим.: В том модуле, который вы хотите поставить во всплывающее окно, имя позиции указывается вручную. В списке позиций шаблона её не будет. В видео инструкции это показано.

Рекомендации по настройке модуля

Настройка окна в режиме Popup.

Чтобы протестировать и посмотреть как выглядит окно выключите запоминание браузером.В этом случае окно будет показываться при каждой загрузке страницы.

Также можно уменьшить время задержки, чтобы не ждать долго.

Заголовок модуля при тестировании можно не скрывать. Так будет понятнее где он стоит.

После окончательной настройки:

  • выключите показ заголовка модуля
  • включите запоминание браузером
  • установите время на сколько запоминать
  • установите нужную задержку

Настройка модального окна в режиме Click. Открытие по клику.

Также оставьте включенным показ заголовка, чтобы видеть выводиться ли модуль на сайте.

Укажите нужный ID для окна.

В нужном месте сайта вставьте ссылку, адресом которой будет служить установленный ID окна (по-умолчанию используется ModalOpen). 

Пример:

 текст ссылки 

Настройка стилей окон.

Если вы имеете хотя бы базовые знания по html и css, то сможете сами изменить внешний вид вашего окна.

Стили для окон заданы в файле /modules/mod_jt_popup/assets/css/default.css

там вы увидите селекторы типа:

#jt_popup1, …2, …3 — они соответствуют стилям окон.

Если в настройках модуля выбран стиль Style 3, значит нужно редактировать #jt_popup3

jt_popupX — это стиль для окна

jt_closeX — это стиль для кнопки закрыть

И в самом конце css файла есть указание для мобильных устройств.На всех устройствах, чей экран менее 800px, всплывающее окно будет занимать 85% ширины экрана.

При необходимости вы можете изменять значения под свои нужды.

Ссылка на основную публикацию