How to Create a Popup Form Using JavaScript

A popup form is a great way to capture the attention of your website visitors.

It can be used to gather information, conduct surveys, or display advertisements.

In this Javascript tutorial, we will show you how to create a popup form using JavaScript.


HTML Markup

To start, we need to create the HTML structure for our form.

We will create a button that will trigger the popup form to appear, and the form itself.

<button id="popup-button">Open Form</button>

<div id="popup-form" style="display: none;">
  <form>
    <label>Name:</label>
    <input type="text" name="name"><br><br>
    <label>Email:</label>
    <input type="email" name="email"><br><br>
    <label>Message:</label>
    <textarea name="message"></textarea><br><br>
    <input type="submit" value="Submit">
  </form>
</div>

CSS Styling

Next, we will add some styles to our form to make it look nice.

You can style it however you like, but for this example, we will keep it simple.

#popup-form {
  background-color: white;
  padding: 20px;
  border: 1px solid black;
  width: 500px;
  height: 300px;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  display: flex;
  flex-direction: column;
  align-items: center;
}

form {
  display: flex;
  flex-direction: column;
  align-items: center;
}

input[type="text"],
input[type="email"],
textarea {
  width: 100%;
  padding: 10px;
  margin-bottom: 20px;
}

JavaScript Code

Finally, we will add the JavaScript code to make the form popup when the button is clicked.

We will use the getElementById method to access the button and form elements and the style.display property to show and hide the form.

const button = document.getElementById("popup-button");
const form = document.getElementById("popup-form");

button.addEventListener("click", function() {
  form.style.display = "flex";
});

form.addEventListener("submit", function(e) {
  e.preventDefault();
  form.style.display = "none";
});

Conclusion

And that’s it!

You now have a working popup form using JavaScript.

You can further customize it by adding more fields, validation, and styling to suit your needs.

With a few lines of code, you can enhance your website and gather valuable information from your visitors.