Introduction
This tip helps you to implement a dialog box using jQuery. It is often required in multiple web applications that on
the click
event, a dialog box is opened. This tip is basically for beginners.
For implementation of the dialog box, we have to follow the below steps:
Step 1
First of all, you have to add
jQuery library in your project. You can download the latest version from jquery.com:
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
You have to add the link of Jquery-ui.css as below:
<link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
Step 2
Make a div
tag in your page and put the content of the dialog box within it.
<div id="dialog" title="Alert">
<p>
Hello this is my first dialog using</p>
</div>
Step 3
Put a button using simple HTML with id “opener
”.
<input type="button" id="opener" value="show Alert" />
Step 4
In the script
tag, put the jQuery code for opening the dialog box:
<script type="text/javascript">
$(document).ready(function () {
$(function () {
$("#dialog").dialog({
autoOpen: false,
modal: true,
show: {
effect: "blind",
duration: 1000
},
hide: {
effect: "explode",
duration: 1000
}
});
});
});
</script>
Step 5
Put on click
event within the script
tag, on clicking which a dialog box is opened.
$("#opener").click(function () {
$("#dialog").dialog("open");
});
Note
- ‘
dialog
’ is the ID of a div
which is opened as
a dialog box. - ‘
opener
’ is the ID of the button on click of which
a dialog box is opened. modal = true
is for disabling the back side
content.show
and hide
are for special effects.
The pictorials view of the dialog box is shown in the figure:
Step 6
If you want your dialog box to be more interactive with colours, you can add
the following function of jQuery:
$("#opener").click(function () {
var state = true;
if (state) {
$("#dialog").animate({
backgroundColor: "purple",
color: "white",
width: 500
}, 1000);
}
});
Now the dialog box looks like:
I hope this will help beginners. Thanks!