If you are a web developer and facing problems in creating a modal box or modal popup using CSS and Javascript, then this article is for you.
A modal is a dialog box or popup window that appears on the screen on any events like mouse clicks, mouse hovers, etc. You can make your web page more interactive with modal boxes and improve the UX of your site. You can use modal boxes if you want to show some messages like error messages, warning messages, confirmation messages, etc on your website.
You can create a modal box using HTML, CSS, and Javascript. You can use Boostrap as well. But, in this article, I am going to show how to create a modal box or modal popup using CSS and Javascript. Let's start the tutorial.
I am going to show you how on clicking a button, a modal popup appears on the screen as a tutorial. I am starting with the HTML code. Find the HTML code given below, and then I will discuss the code thoroughly.
Here, I have added a button so that on clicking the button the modal-box / popup appears. Now, we need another <div> element for creating the modal-box and there I have used an ( X ) sign for creating the close button and have added classes and ids so that I can apply styles and use Javascript.
Now, check the CSS code given below.
Now, we want that on clicking the button modal popup appears and on clicking the close button it disappears. For handling this job, you need to use Javascript. So, check the Javascript code given below.
Now, we want to trigger functions on clicking the buttons so that the modal popup appears and disappears. So, you have to get the respective elements to trigger the events. To get the elements, you have to declare variables and use getElementById or getElementByClassName whichever is applicable. You have set the display property of .modal-box to 'none', now the function to be triggered on clicking the 'click' button, should change that display property to 'block'.
You also have to add functions for closing the modal popup. Now, you can find I have added two functions for closing the modal popup. The first one is triggered when the close button is clicked and the display property is changed into 'none' and the modal popup closes. The other function is triggered when the user clicks anywhere outside the modal popup.
Now, you are ready to create an awesome modal popup. I hope everything is clear to you but If you find anything wrong or you don't understand anything, let me know through your comments.
Happy coding 😄 .
No comments:
Post a Comment