- Создаем всплывающие окна для сайта — Magnific Popup
- Подключение Magnific Popup
- Типы модальных окон
- Тип контента в окне — Inline
- Magnific popup как настроить
- About
- Magnific Popup
- Magnific Popup is a responsive lightbox & dialog script with focus on performance and providing best experience for user with any device (for jQuery or Zepto.js).
- Examples
- Single image lightbox
- Lightbox gallery
- Zoom-gallery
- Popup with video or map
- Dialog with CSS animation
- Dialog example
- Popup with form
- Ajax popup
- Modal popup
- Modal dialog
- Error handling
- What makes this plugin different?
- Light and modular
- Content is resized with CSS
- High-DPI (Retina) display support
- Conditional lightbox
- Memory management
- Browser support
- License
- Bugs & contributing
- Updates
Создаем всплывающие окна для сайта — Magnific Popup
Приветствую всех посетителей моего блога! Писать статьи получается очень редко, что не есть хорошо. Уже боюсь что-то обещать, как раньше — писать буду чаще и все такое. Причина вся та же — нехватка времени. Ну ладно, сегодняшний пост не об этом. Поговорим о всплывающих окнах для сайта. На просторах интернета практически нет сайтов, которые не используют всплывающие (модальные) окна. В связи с этим я посчитал, что данная тема для веб-разработчика очень важна. Скриптов модальных окон в сети интернет очень много. Какой из них выбрать, чтобы было проще подключать, проще пользоваться, обладал широкими возможностями и т.д.? Я для себя такой нашел…
Magnific Popup — jQuery плагин всплывающих окон, сделанный с акцентом на производительность и удобство пользования. Так кратко описывает автор скрипта — Дмитрий Семенов и я с ним абсолютно согласен. Я уже достаточно долго использую Magnific Popap для модальных окон и успел в этом убедиться.
Вообще хотелось бы отметить, что Magnific очень популярен, как в рунете, так и в буржуйнете, не смотря на то, что разработчик русскоговорящий. В общем, Magnific Popup заслужил то, чтобы я про него написал отдельный пост.
Вот основные преимущества плагина, которые я могу выделить от себя:
- Легкость и модульность. Минимизированная версия скрипта со всеми включенными модулями весит всего лишь
20 кб. В процессе компиляции (об этом поговорим чуть ниже) вы можете выбрать только те модули, которые вам нужны. Модули это типы всплываемых окон:
- Inline — обычные блочные окна, содержащие любой контент;
- Image — всплывание изображений;
- Ajax — подгрузка данных в окне посредством технологии Ajax;
- Iframe — подгрузка данных окна в Iframe, например, видео Youtube;
- Gallery — по сути Image, но с возможностью листать фото с помощью стрелок, т.е. минигалерея;
- High-DPI (retina) — только для типа Image. Данный модуль позволяет показывать изображения с высоким разрешением на устройствах с дисплеями разной плотностью пикселей. Честно говоря, с этим я не разобрался, так что особо нечего сказать по данному поводу. Надо будет выделить время и разобраться.
- Image zoom animation — анимация при всплывании изображения. Если кому не нужна анимация можно не включать данный модуль в пакет.
Для того, чтобы сачать Magnific Popup переходим на официальный сайт разработчика. Жмем по ссылке «Build tool» и в модальном окне выбираем нужные нам модули. После всего жмем «Generate build» и получаем код плагина. Данный код необходимо скопировать в редактор кода, например, Notepade++ или Sublime Text и сохранить с расширением «.js«. Также в этом же окне билда вам надо сохранить код CSS. Для этого щелкаем правом кнопкой мыши по ссылке «CSS version» и сохраняем файл стилей. Если вы пользуетесь препроцессором, то сохраните файл «Sass version«. Если не получается сохранить перейдите по ссылке сохраните код самостоятельно в редакторе кода.
Подключение Magnific Popup
Подключить плагин и начать работать с ним достаточно просто. Вообще на сайте есть подробная документация, правда она на английском. Но я скажу вам — чтобы заниматься веб-разработкой крайне важно знать английский язык на техническом уровне. Без этого никуда. Для меня лично не составляет труда изучить документацию по скриптам на английском языке. В конце концов есть также гугл переводчик, которым можно воспользоваться, если что-то непонятно.
В данной статье я рассмотрю только те моменты модальных окон, с которыми я разобрался и которые активно внедряю в процессе разработки сайтов. И так давайте начнем.
Подключаем файл плагина и файл стилей Magnific Popup. Если у вас не подключена библиотека jQuery, то обязательно следует подключить и ее. В общем, здесь подключение ничем не отличается от подключения любого другого скрипта jQuery. Про подключение стилей и скриптов я написал отдельную статью, советую ее почитать.
Типы модальных окон
Тип контента в окне — Inline
Далее нам следует инициализировать наш плагин. Для этого нам нужно определиться с типом всплываемого контента. Давайте вызовем в модальном окне обычный текст. Тогда код инциализации будет для контента с типом — Inline.
Как видим событие вызова модального окна вешается на объект с классом «popup-content«. Поэтому создадим его, например, это будет ссылка с якорем на вызываемый блок с id=»text-popup».
И еще кое что. Для того, чтобы наше окно стало видно нам необходимо в файл стилей «magnific-popup.css» добавить следующий код:
Данное правило задает фоновый цвет окну и отступы. Их изначально его нет в файле стилей, т.к. само окно можно оформить на свое усмотрение.
В результате у нас открывается модальное окно с нашим текстом. Все довольно просто.
Источник
Magnific popup как настроить
Magnific Popup Repository
Fast, light and responsive lightbox plugin, for jQuery and Zepto.js.
Optionally, install via Bower bower install magnific-popup or npm: npm install magnific-popup . Ruby gem: gem install magnific-popup-rails .
If you created an extension for some CMS, email me and I’ll add it to this list.
Location of stuff
- Generated popup JS and CSS files are in folder dist/. (Online build tool is on documentation page).
- Source files are in folder src/. They include Sass CSS file and js parts (edit them if you wish to submit commit).
- Website (examples & documentation) is in folder website/.
- Documentation page itself is in website/documentation.md (contributions to it are very welcome).
Using Magnific Popup?
If you used Magnific Popup in some interesting way, or on site of popular brand, I’d be very grateful if you email me a link to it.
To compile Magnific Popup by yourself, first of make sure that you have Node.js, Grunt.js, Ruby and Jekyll installed, then:
Go inside Magnific Popup folder that you fetched and install Node dependencies
cd Magnific-Popup && npm install
Now simply run grunt to generate JS and CSS in folder dist and site in folder _site/ .
- Run grunt watch to automatically rebuild script when you change files in src/ or in website/ .
- If you don’t have and don’t want to install Jekyll, run grunt nosite to just build JS and CSS files related to popup in dist/ .
Script is MIT licensed and free and will always be kept this way. But has a small restriction from me — please do not create public WordPress plugin based on it(or at least contact me before creating it), because I will make it and it’ll be open source too (want to get notified?).
Please report bugs via GitHub and ask general questions through Stack Overflow. Feel free to submit commit pull-request, even the tiniest contributions to the script or to the documentation are very welcome.
About
Light and responsive lightbox script with focus on performance.
Источник
Magnific Popup
Magnific Popup is a responsive lightbox & dialog script with focus on performance and providing best experience for user with any device
(for jQuery or Zepto.js).
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.
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.
Popup with form
Entered data is not lost if you open and close the popup or if you go to another page and then press back browser button.
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.
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.
Don’t forget to check out my new article about this plugin on the Smashing Magazine.
What makes this plugin different?
Light and modular
You can choose to include only the features that you need using the online build tool 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.
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.
Browser support
Tested on desktop: Chrome, Safari, FF, Opera, IE8+, partial support of IE7 (works, but some visual layout features, like vertical centering, are missing). Mobile: default browser in Android 2.3+, iOS5+, Blackberry 10+, WP7+, mobile Opera and Chrome on Android. If you noticed any bug, please open an issue on GitHub
License
Script is available under MIT license and will always be kept this way.
But please do me a favor and do not create a public WordPress plugin based on it, because I will make it soon and it will be open souce too. (Want to get notified?).
Bugs & contributing
Please report bugs via GitHub and ask general questions through StackOverflow. Feel free to submit commit, even the tiniest contributions to the script or to the documentation are very welcome.
Special thanks to:
- Lokesh Dhakar for original Lightbox script.
- Chris Coyier for awesome CSS techniques.
- Brad Frost for conditional lightbox technique.
Updates
If you wish to get notified about important plugin updates, you may star and watch the repository on GitHub, follow me on Twitter, or join my tiny Mailchimp email newsletter that I send 3-4 times a year.
Источник