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.
To create a modal using jQuery, follow the steps given below.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Let’s perform the steps above in the following widget and understand how the jQuery modal pop-up works.
In the HTML file:
Line 6: Create a modalBtn button. This button is used to open the modal.
Lines 9–15: These contain the modal. It has two div elements, the parent div with class modal and the child div with class modalContent, which holds the modal content. A code for the cross(x) icon is on line 11. It is used to close the modal.
In the CSS file:
Lines 1–7: Lies the .modal style. The modal display is initially set to none as 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. The width is defined, and margin is set to auto; this centers the modal horizontally on the page.
Lines 9–15: These contain the .modalContent styling. The background-color, .margin, .padding, border, and width are all set to make the content look good.
Lines 17–22: We style the .closeBtn. Its color is set appropriately. The float: right floats it to the top right corner of the modal. The font-size determines its size, while the font-weight defines its opacity.
Lines 24–28: Define the closeBtn hover and focus style. Only the color was changed, and an additional style of text-decoration was set to none.
Lines 30–32: The h2 text-align was set to center to 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: none of the modal class to the display: block to 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: block of the modal class to the display: none to 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