How to make a jQuery modal pop-up
Modals provide a way to focus the user’s attention on a specific task or information while temporarily disabling interactions with the rest of the web page. It is often used to display additional information, request user input, or confirm action on a web page.
To handle their functionality, modals are created with HTML, CSS, and any programming language.
jQuery modal pop-up
To create a modal using jQuery, follow the steps given below.
- Step 1: Include the jQuery library in the project. Include it locally or use
. For example, to utilize the CDN method, include the following line of code in the head of the HTML file.CDN Content Delivery Network
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
- Step 2: Create the HTML markup for the modal pop-up
- Step 3: Style the modal to make it look well.
- Step 4: Include the jQuery code to activate the modal functionality.
Example
Let’s perform the steps above in the following widget and understand how the jQuery modal pop-up works.
Explanation
In the HTML file:
-
Line 6: Create a
modalBtnbutton. This button is used to open the modal. -
Lines 9–15: These contain the modal. It has two
divelements, the parentdivwith classmodaland the childdivwith classmodalContent, which holds the modal content. A code for thecross(x)icon is on line 11. It is used to close the modal.
In the CSS file:
-
Lines 1–7: Lies the
.modalstyle. The modal display is initially set tononeas it’s not part of the web page. It’s only there to draw the user’s attention to its content. The modal is usually opened with a button. Thewidthis defined, andmarginis set to auto; this centers the modal horizontally on the page. -
Lines 9–15: These contain the
.modalContentstyling. Thebackground-color,.margin,.padding,border, andwidthare all set to make the content look good. -
Lines 17–22: We style the
.closeBtn. Its color is set appropriately. Thefloat: rightfloats it to the top right corner of the modal. Thefont-sizedetermines its size, while thefont-weightdefines its opacity. -
Lines 24–28: Define the
closeBtnhover and focus style. Only thecolorwas changed, and an additional style oftext-decorationwas set tonone. -
Lines 30–32: The
h2text-alignwas set tocenterto move it to the center of the modal.
In the JavaScript file:
-
Lines 6–8: The modal’s display was attached to the button’s click event. This line changes the
display: noneof the modal class to thedisplay: blockto make the modal visible. -
Lines 11–13: The modal’s disappearance was attached to the close button and modal body click event. This line changes the
display: blockof the modal class to thedisplay: noneto make the modal invisible. -
Lines 16–18: This line prevents all event triggers from clicking inside the modal.
We have a basic jQuery modal pop-up. It can further be customized and enhanced based on requirements.
Free Resources