Bootstrap modal form

Options

There are certain options which can be passed to Bootstrap method to customize the functionality of a modal. Options can be passed via data attributes or JavaScript.

For setting the modals options via data attributes, just append the option name to , such as , , and so on.

Name Type Default Value Description
backdrop boolean or the string true Includes a modal-backdrop (black overlay area) element. Alternatively, you may specify for a backdrop which doesn’t close the modal on click.
keyboard boolean true Closes the modal window on press of escape key.
focus boolean true Puts the focus on the modal when initialized.
show boolean true Shows the modal when initialized or activate.

Data attributes provides an easy way for setting the modal options, however JavaScript is the more preferable way as it prevents you from repetitive work. See the method in the section below to know how to set the options for modals using JavaScript.

In the following example we’ve set the option to (line no-5) which prevents the modal from closing when clicking outside of the modal i.e. the black overlay area.

Эффект затухания

Теперь давайте применим ещё одну фишку, а именно, эффект затухания. Для этого div-у модального окна припишем класс fade:

<div id="modal" class="modal hide fade">
	<div class="modal-header">
		<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
		<h2>Lorem Ipsum</h2>
	</div>
	<div class="modal-body">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
		Donec placerat sem ipsum, ut faucibus nulla. Nullam mattis volutpat
		dolor, eu porta magna facilisis ut. In ultricies, purus sed pellentesque
		mollis, nibh tortor semper elit, eget rutrum purus nulla id quam.</p>
	</div>
</div>

Теперь открытие и закрытие нашего модального окна будет сопровождаться приятной для глаз анимацией. Данный эффект реализован в большей степень через CSS3.

События, связанные с модальным окном

Событие сработатывает при вызове метода .

$('#modal-example').on('show.bs.modal', function() {
    // что-то делаем...
});

Событие сработатывает после завершения работы метода , то есть когда окно открыто, и все его CSS-стили загружены.

$('#modal-example').on('shown.bs.modal', function() {
    // что-то делаем...
});

Событие сработатывает при вызове метода .

$('#modal-example').on('hide.bs.modal', function() {
    // что-то делаем...
});

Событие сработатывает после завершения работы метода .

$('#modal-example').on('hidden.bs.modal', function() {
    // что-то делаем...
});

Если окно было открыто по событию клика, то элемент, открывший его, становится доступным через свойство события .

<button type="button" class="btn btn-primary" data-toggle="modal"
        data-target="#modal-example">
    Открыть модальное окно
</button>

<!-- Модальное окно -->
<div class="modal fade" id="modal-example" tabindex="-1"
     role="dialog" aria-hidden="true">
    ..........
</div>
$(document).ready(function() {
    // событие при открытии модального окна
    $('#modal-example').on('show.bs.modal', function (e) {
        if (e.relatedTarget == undefined) {
            alert('Окно сейчас будет открыто без клика по элементу');
        } else {
            alert('Окно сейчас будет открыто после клика на ' + e.relatedTarget.nodeName);
        }
    });
});

Поиск:
Bootstrap • CSS • HTML • JavaScript • Web-разработка • Верстка • Фреймворк • Модальное окно • Modal

Explanation of Code

To activate a Bootstrap modal via data attributes we basically need two components — the controller element like a button or link, and the modal element itself.

  • The outermost container of every modal in a document must have a unique id (in this case , line no-5), so that it can be targeted via (for buttons) or (for hyperlinks) attribute of the controller element (line no-2).
  • The attribute is required to add on the controller element (line no-2), like a button or an anchor, along with a attribute or to target a specific modal to toggle.
  • The class (line no-6) sets the width as well as horizontal and vertical alignment of the modal box. Whereas the class sets the styles like text and background color, borders, rounded corners etc.

Rest of the thing is self explanatory, such as the element defines a header for the modal that usually contains a modal title and a close button, whereas the element contains the actual content like text, images, forms etc. and the element defines the footer that typically contains action buttons for the user.

Note: The class on the element adds a fading and sliding animation effect while showing and hiding the modal window. If you want the modal that simply appear without any effect you can just remove this class. Also, when modals become too long for the user’s viewport or device, they scroll independent of the page itself.

Контроль появления модального окна

Предположим, что модальное окно должно появляться в результате нажатия кнопки. Для этого, в первую очередь, чтобы изначально скрыть блок окна, присвоим ему класс hide:

<div id="modal" class="modal hide">
	<div class="modal-header">
		<h2>Lorem Ipsum</h2>
	</div>
	<div class="modal-body">
		<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit.
		Donec placerat sem ipsum, ut faucibus nulla. Nullam mattis volutpat
		dolor, eu porta magna facilisis ut. In ultricies, purus sed pellentesque
		mollis, nibh tortor semper elit, eget rutrum purus nulla id quam.</p>
	</div>
</div>

Теперь можно добавить и кнопку:

<a href="#modal" role="button" class="btn" data-toggle="modal">Click Me</a>

Тут прошу обратить ваше внимание на HTML5 атрибут data-toggle, где мы прописываем id блока модального окна. Ну а теперь, чтобы активировать плагин, добавляем js скрипт:

Ну а теперь, чтобы активировать плагин, добавляем js скрипт:

$('document').ready(function(){
    $('#modal').modal();
});

Теперь, при нажатии на кнопку мы получим примерно такое отображение модального окна:

Большое и маленькое модальное окно

<p>
    <button class="btn btn-primary" data-toggle="modal" data-target="#modal-example-lg">
        Большое окно
    </button>
    <button class="btn btn-primary" data-toggle="modal" data-target="#modal-example-sm">
        Маленькое окно
    </button>
</p>
<!-- Большое окно -->
<div class="modal fade" id="modal-example-lg" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-lg" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Заголовок окна</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Закрыть">
                    <span aria-hidden="true">&times;</span>
                </button>

            </div>
            <div class="modal-body">
                <p>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                    eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim
                    ad minim veniam, quis nostrud exercitation ullamco laboris nisi
                    ut aliquip ex ea commodo consequat.
                </p>
                <p>
                    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                    eiusmodtempor incididunt ut labore et dolore magna aliqua. Ut enim
                    ad minim veniam, quis nostrud exercitation ullamco laboris nisi
                    ut aliquip ex ea commodo consequat.
                </p>
            </div>
        </div>
    </div>
</div>
<!-- Маленькое окно -->
<div class="modal fade" id="modal-example-sm" tabindex="-1" role="dialog">
    <div class="modal-dialog modal-sm" role="document">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title">Заголовок окна</h4>
                <button type="button" class="close" data-dismiss="modal" aria-label="Закрыть">
                    <span aria-hidden="true">&times;</span>
                </button>
            </div>
            <div class="modal-body">
                Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
                eiusmodtempor incididunt ut labore et dolore magna aliqua.
            </div>
        </div>
    </div>
</div>

Creating Modals with Bootstrap

Modal is basically a dialog box or popup window that is used to provide important information to the user or prompt user to take necessary actions before moving on. Modals are widely used to warn users for situations like session time out or to receive their final confirmation before going to perform any critical actions such as saving or deleting important data.

You can easily create very smart and flexible dialog boxes with the Bootstrap modal plugin. The following example oulines the basic structure to create a simple modal with a header, message body and the footer containing action buttons for the user.

Example

Try this code

— If you try out the above example, it will launches the modal window automatically when the DOM is fully loaded via JavaScript. The output will look something like this:

Tip: Always try to place your modal HTML in a top-level position in your document, preferably before closing of the tag (i.e. ) to avoid interference from other elements, otherwise it may affect modal’s appearance or functionality.

Check out the snippets section for examples of some beautifully designed Bootstrap modals.

Параметры модального окна

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

Параметр Описание
Значение по умолчанию: . Накладывает темный фон над всем содержимым веб-страницы, поверх которого отображается модальное окно. У данного параметра есть дополнительное значение , которое запрещает закрывать модальное окно при клике за его пределами. Параметр также можно установить с помощью атрибута data-backdrop.
Значение по умолчанию: . Закрывает модальное окно при нажатии клавиши . Данный параметр также можно установить с помощью атрибута .
Значение по умолчанию: . Отображает модальное окно сразу после его инициализации. Данный параметр также можно установить с помощью атрибута .

Events

Bootstrap’s modal class includes few events for hooking into modal functionality.

Event Description
show.bs.modal This event fires immediately when the show instance method is called.
shown.bs.modal This event is fired when the modal has been made visible to the user. It will wait until the CSS transition process has been fully completed before getting fired.
hide.bs.modal This event is fired immediately when the hide instance method has been called.
hidden.bs.modal This event is fired when the modal has finished being hidden from the user. It will wait until the CSS transition process has been fully completed before getting fired.

The following example displays an alert message to the user when fade out transition of the modal window has been fully completed.

Example

Try this code

Tip: See also the section for more examples on modals, like setting vertical alignment, changing default width, embedding video, etc.

5 последних уроков рубрики «Разное»

  • Выбрать хороший хостинг для своего сайта достаточно сложная задача. Особенно сейчас, когда на рынке услуг хостинга действует несколько сотен игроков с очень привлекательными предложениями. Хорошим вариантом является лидер рейтинга Хостинг Ниндзя — Макхост.

  • Как разместить свой сайт на хостинге? Правильно выбранный хороший хостинг — это будущее Ваших сайтов

    Проект готов, Все проверено на локальном сервере OpenServer и можно переносить сайт на хостинг. Вот только какую компанию выбрать? Предлагаю рассмотреть хостинг fornex.com. Отличное место для твоего проекта с перспективами бурного роста.

  • Создание вебсайта — процесс трудоёмкий, требующий слаженного взаимодействия между заказчиком и исполнителем, а также между всеми членами коллектива, вовлечёнными в проект. И в этом очень хорошее подспорье окажет онлайн платформа Wrike.

  • Подборка из нескольких десятков ресурсов для создания мокапов и прототипов.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *

Adblock
detector