How to Create a Pop-up Form With CSS and JavaScript

Pop-up forms are an essential part of modern web design, serving various purposes such as collecting user information, displaying notifications, or promoting products.

They can improve user engagement and increase conversions, making them an important tool for website owners.

In this tutorial, we will show you how to create dynamic pop-up forms using CSS and JavaScript.

By the end of this tutorial, you will have a basic understanding of how to create a pop-up form that appears and disappears based on user interaction.


CSS

To create a pop-up form, we first need to define its layout and appearance using CSS.

The following is an example of the CSS code you can use to style your pop-up form:

.popup-container {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  background-color: #fff;
  padding: 20px;
  border-radius: 10px;
  box-shadow: 0 0 10px #000;
  display: none;
}

.show-popup {
  display: block;
}

In the above CSS code, we have defined the style for our pop-up container.

The .popup-container class sets the position of the form to be fixed in the center of the screen.

The transform property is used to translate the form’s position by 50% horizontally and vertically.

The background color of the form is set to white, and a padding of 20 pixels is added to create space between the form’s content and its border.

The border-radius property is used to give the form rounded edges, while the box-shadow property is used to add a drop shadow effect.

Finally, the display property is set to none to ensure that the form is hidden by default.

The .show-popup class is used to display the form when it is needed.

JavaScript

Now that we have defined the appearance of our pop-up form, it’s time to add the JavaScript code to make it dynamic. The following is an example of the JavaScript code you can use to create a pop-up form:

var popupContainer = document.querySelector(".popup-container");
var showPopupBtn = document.querySelector(".show-popup-btn");

showPopupBtn.addEventListener("click", function() {
  popupContainer.classList.add("show-popup");
});

popupContainer.addEventListener("click", function(e) {
  if (e.target == popupContainer) {
    popupContainer.classList.remove("show-popup");
  }
});

In the above JavaScript code, we first select the pop-up container and the button that will show the form using the querySelector method.

We then add an event listener to the button that will add the .show-popup class to the form when it is clicked.

Next, we add an event listener to the form itself that will remove the .show-popup class and hide the form when the user clicks outside of it.

This is done by checking if the target of the click event is the form itself.


Conclusion

In this tutorial, we have shown you how to create a dynamic pop-up form using CSS and JavaScript.