how to create modals with Bootstrap
In this tutorial you will learn how to create modals with Bootstrap.
Creating Modals with Bootstrap
Modals are basically a dialog box that is used to provide important information to the user or prompt user to take necessary actions before moving on. Modal windows 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 will show you how to create a simple modal with a header, message body and the footer containing action buttons for the user.
Example
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Do you want to save changes you made to document before closing?</p>
<p class="text-warning"><small>If you don't save, your changes will be lost.</small></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
— The above example launches the modal window when the DOM is fully loaded via JavaScript. The output will look something like this:

Activate Modals via Data Attributes
You can activate a Bootstrap modal by clicking on the button or link via data attributes without writing any JavaScript code. See the following example:
Example
<!-- Button HTML (to Trigger Modal) -->
<a href="#myModal" role="button" class="btn btn-large btn-primary" data-toggle="modal">Launch Demo Modal</a>
<!-- Modal HTML -->
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Confirmation</h4>
</div>
<div class="modal-body">
<p>Do you want to save changes you made to document before closing?</p>
<p class="text-warning"><small>If you don't save, your changes will be lost.</small></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
</div>
The above example launches the modal window on click of the "Launch Demo Modal" button. Let's go through each part of this modal code one by one for a better understanding.
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
id="myModal"), so that it can be targeted viadata-target(for buttons) orhref(for hyperlinks) attribute of the controller element. - The attribute
data-toggle="modal"is required to add on the controller element, like a button or an anchor, along with a attributedata-target="#myModal"orhref="#myModal"to target a specific modal to toggle. - The
.modal-dialogclass sets the width as well as horizontal and vertical alignment of the modal box. Whereas the class.modal-contentsets the styles like text and background color, borders, rounded corners etc.
Rest of the thing is self explanatory, such as the .modal-header element defines a header for the modal that usually contains a modal title and a close button, whereas the .modal-bodyelement contains the actual content like text, images, forms etc. and the .modal-footerelement defines the footer that typically contains action buttons for the user.
Note:The .fade class on the .modal 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.
Activate Modals via JavaScript
You may also activate a Bootstrap modal window via JavaScript — just call the modal()Bootstrap method with the modal "id" or "class" selector in your JavaScript code.
Example
<script type="text/javascript">
$(document).ready(function(){$(".btn").click(function(){$("#myModal").modal('show');});
});
</script>
Changing the Sizes of Modals
Bootstrap gives you option further to scaling a modal up or down. You can make modals larger or smaller by adding an extra class .modal-lg or .modal-sm on .modal-dialog.
Example
<!-- Large modal -->
<button class="btn btn-primary" data-toggle="modal" data-target="#largeModal">Large modal</button>
<div id="largeModal" class="modal fade bs-example-modal-lg" tabindex="-1" role="dialog">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Large Modal</h4>
</div>
<div class="modal-body">
<p>Add the <code>.modal-lg</code> class on <code>.modal-dialog</code> to create this large modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary">OK</button>
</div>
</div>
</div>
</div>
<!-- Small modal -->
<button class="btn btn-primary" data-toggle="modal" data-target="#smallModal">Small modal</button>
<div id="smallModal" class="modal fade" tabindex="-1" role="dialog">
<div class="modal-dialog modal-sm">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title">Small Modal</h4>
</div>
<div class="modal-body">
<p>Add the <code>.modal-sm</code> class on <code>.modal-dialog</code> to create this small modal.</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="button" class="btn btn-primary">OK</button>
</div>
</div>
</div>
</div>
Changing Modal Content Based on Trigger Button
Often several modal on a web page has almost same content with minor differences.
You can use the modal events to create slightly different modal windows based on the same modal HTML. The following example will change the title of the modal window according to the trigger button's data-title attribute value.
Example
<script type="text/javascript">
$(document).ready(function(){$("#myModal").on('show.bs.modal', function(event){// Get button that triggered the modal
var button = $(event.relatedTarget);
// Extract value from data-* attributes
var titleData = button.data('title');$(this).find('.modal-title').text(titleData + ' Form');});
});
</script>
Options
There are certain options which may be passed to modal() Bootstrap method to customize the functionality of a modal window.
| Name | Type | Default Value | Description |
|---|---|---|---|
| backdrop | boolean or the string 'static' |
true | Includes a modal-backdrop (black overlay area) element. Alternatively, you may specify static for a backdrop which doesn't close the modal on click. |
| keyboard | boolean | true | Closes the modal window on press of escape key. |
| show | boolean | true | Shows the modal when initialized or activate. |
| remote | URL | false | Deprecated If a remote url is provided, content will be loaded one time via jQuery's load method and injected into the '.modal-content' div. |
You may set these options either through the use of data attributes or JavaScript. For setting the modals options via data attributes, just append the option name to data-, like data-backdrop="static", data-keyboard="false" etc.
However, JavaScript is the more preferable way for setting these options as it prevents you from repetitive work. See the modal's method .modal(options) in the section below to know how to set the options for modals using the JavaScript.
If you're using the data api for setting the options for modal window, you may alternatively use the "href" attribute to provide the URL of remote source, like this:
Example
<!-- Button HTML (to Trigger Modal) -->
<a href="remote.html" role="button" class="btn btn-large btn-primary" data-toggle="modal" data-target="#myModal">Launch Demo Modal</a>
<!-- Modal HTML -->
<div id="myModal" class="modal fade">
<div class="modal-dialog">
<div class="modal-content">
<!-- Content will be loaded here from "remote.php" file -->
</div>
</div>
</div>
Note:The remote option for the Bootstrap modals is deprecated since v3.3.0 and will be removed in v4. Use the client-side templating or a data binding framework instead, or call the jQuery.load method yourself.
Methods
These are the standard bootstrap's modals methods:
.modal(options)
This method activates the content as a modal. It also allows you to set options for them.
The jQuery code in the following example will prevent the modal from closing when a user clicks on the backdrop i.e. black overlay area behind the modal.
Example
<script type="text/javascript">
$(document).ready(function(){$(".launch-modal").click(function(){$("#myModal").modal({backdrop: 'static'
});
});
});
</script>
The following jQuery code will prevent the modal from closing on press of the escape key.
Example
<script type="text/javascript">
$(document).ready(function(){$(".launch-modal").click(function(){$("#myModal").modal({keyboard: false
});
});
});
</script>
The jQuery code in the following example will create a modal in which content of the modal will be inserted from a remote file upon activation.
Example
<script type="text/javascript">
$(document).ready(function(){$(".launch-modal").click(function(){$("#myModal").modal({remote: '../remote.php'
});
});
});
</script>
.modal('toggle')
This method toggles a modal window manually.
Example
<script type="text/javascript">
$(document).ready(function(){$(".toggle-modal").click(function(){$("#myModal").modal('toggle');});
});
</script>
.modal('show')
This method can be used to open a modal window manually.
Example
<script type="text/javascript">
$(document).ready(function(){$(".open-modal").click(function(){$("#myModal").modal('show');});
});
</script>
.modal('hide')
This method can be used to hide a modal window manually.
Example
<script type="text/javascript">
$(document).ready(function(){$(".hide-modal").click(function(){$("#myModal").modal('hide');});
});
</script>
.modal('handleUpdate')
This method readjusts the modal's position to counter the jerk that is occurring due to the appearance of the viewport scrollbar in case if the modal height changes in such a way that it becomes higher than the viewport height while it is open.
A common example of this scenario is showing the hidden elements inside the modal via JavaScript or loading content inside the modal using Ajax after activation.
Example
<script type="text/javascript">
$(document).ready(function(){$(".show-text").click(function(){$('#myModal').find(".lots-of-text").toggle();$('#myModal').modal('handleUpdate')});
});
</script>
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. |
| loaded.bs.modal | This event is fired when the modal has loaded content using the remoteoption. |
The following example displays an alert message to the user when fade out transition of the modal window has been fully completed.
Example
<script type="text/javascript">
$(document).ready(function(){$("#myModal").on('hidden.bs.modal', function(){alert("Modal window has been completely closed.");});
});
</script>
Tip:See also the Bootstrap FAQ section for more examples on modals, like setting vertical alignment, changing default width, embedding video, etc.
how to create modals with Bootstrap的更多相关文章
- Bootstrap库之Modals
Bootstrap库之Modals. Bootstrap是Twitter推出的一个开发工具包,包含了一些比较常用的CSS,JavaScript代码.使用Bootstrap可以加快前端开发的速度.本站( ...
- bootstrap弹框
http://v3.bootcss.com/javascript/#modals 参考bootstrap官网 模态框做php后端 前端一直不行,但是很多时候 用到ajax都要用到弹框,一直在代码里面找 ...
- AngularJS从构建项目开始
AngularJS从构建项目开始 AngularJS体验式编程系列文章,将介绍如何用angularjs构建一个强大的web前端系统.angularjs是由Google团队开发的一款非常优秀web前端框 ...
- How to handle Imbalanced Classification Problems in machine learning?
How to handle Imbalanced Classification Problems in machine learning? from:https://www.analyticsvidh ...
- Create Dynamic Modal Dialog Form in AdminLTE Bootstrap template
原文地址 Create modal dialog form in jquery using bootstrap framework, slightly different from the usual ...
- [转]ASP.NET MVC 5 List Editor with Bootstrap Modals
本文转自:https://www.codeproject.com/articles/786085/asp-net-mvc-list-editor-with-bootstrap-modals With ...
- Bootstrap Modals(模态框)
http://www.runoob.com/bootstrap/bootstrap-v2-modal-plugin.html 描述 Bootstrap Modals(模态框)是使用定制的 Jquery ...
- bootstrap学习--模态弹出框modals轮子
1.点击按钮型 <link rel="stylesheet" href="lib/bootstrap/css/bootstrap.min.css"> ...
- js学习之--Bootstrap Modals(模态框)
http://www.runoob.com/bootstrap/bootstrap-v2-modal-plugin.html http://outofmemory.cn/bootstrap/tutor ...
随机推荐
- 剑指Offer(书):删除链表的节点
题目:在O(1)的时间内删除列表节点. /** * 步骤: * 1.检查head与removeNode节点是否为空 * 2.检查removeNode的后一个节点是否为空,不为空则使用后一个节点的值覆盖 ...
- 【BZOJ 1588】[HNOI2002] 营业额统计(Treap)
Description 营业额统计 Tiger最近被公司升任为营业部经理,他上任后接受公司交给的第一项任务便是统计并分析公司成立以来的营业情况. Tiger拿出了公司的账本,账本上记录了公司成立以来每 ...
- luogu2234 [HNOI2002]营业额统计
treap水过 #include <iostream> #include <cstdlib> #include <cstdio> using namespace s ...
- zju 3209 dancing links 求取最小行数
题目可以将每一个格子都看做是一列,每一个矩形作为1行,将所有格子进行标号,在当前矩形中的格子对应行的标号为列,将这个点加入到十字链表中 最后用dlx求解精确覆盖即可,dance()过程中记得剪枝 #i ...
- bzoj 1500 [NOI 2005] 维修数列
题目大意不多说了 貌似每个苦逼的acmer都要做一下这个splay树的模版题目吧 还是有很多操作的,估计够以后当模版了.... #include <cstdio> #include < ...
- bzoj 1503[NOI 2004] 郁闷的出纳员
题目大意: 给4种操作 I:添加一个员工工资信息 A:增加所有员工的工资 S:减少所有员工的工资 F:询问工资第k高的员工的工资情况 自己做的第一道splay树的题目,初学找找感觉 #include ...
- CSU1350 To Add which?
题目链接: http://acm.csu.edu.cn/OnlineJudge/problem.php?id=1350 这题目因为每一个数都跟相邻的数有关,所以可以从左到右和从右到左一次扫一遍即可 代 ...
- PHP中的字符串替换(str_replace)
/*替换 字符串处理 str_replace() */ $num = 0; $str = "http://www.phpbrother.net/php/demo.php";$st ...
- maven 编译出错 Failed to execute goal org.apache.maven.plugins:maven-clean-plugin:2.5:clean
eclipse在使用maven的tomcat控件编译java程序时,报错 Failed to execute goal org.apache.maven.plugins:maven-clean-plu ...
- 深入理解计算机操作系统——第11章:全球IP英特网
全球IP英特网 (1)每台英特网主机都运行实现TCPIP协议的软件. (2)英特网的客户端和服务器混合使用套接字接口函数和Unix IO函数来进行通信. (3)套接字函数典型的是作为陷入内核的系统调用 ...