Building a Contact Form with HTML, CSS, and JavaScript
Tags: webdev, javascript, beginners, programming
Published: 2024-02-02 07:45:00

Creating a contact form for your website is a crucial aspect of engaging with your audience. In this blog post, we'll walk through the process of building a simple and stylish contact form using HTML, CSS, and JavaScript. Additionally, we'll use a backend API to handle form submissions.

## HTML Structure

Let's start with the HTML structure. This code includes the basic layout of the contact form along with a response message div to display the API's feedback.

```html
<!DOCTYPE html>
<html lang="en">

<head>
    <!-- Meta tags and stylesheets -->
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Contact Form</title>
    <link rel="stylesheet" href="style.css" />
</head>

<body>
    <header>
        <h1>Contact Form</h1>
    </header>
    
    <div id="responseMessage"></div> <!-- Display API response message -->

    <form id="contactForm">
        <input name="name" type="text" id="name" class="feedback-input" placeholder="Name" required />
        <input name="email" type="email" id="email" class="feedback-input" placeholder="Email" required />
        <textarea name="message" id="message" class="feedback-input" placeholder="Comment" required></textarea>
        <input type="submit" value="SUBMIT" />
    </form>

    <!-- Additional details or footer -->
    <footer>
        <p>&copy; 2024 Manthan Ankolekar | Contact Form.</p>
    </footer>

    <!-- JavaScript file -->
    <script src="script.js"></script>
</body>

</html>
```

## CSS Styling

Next, we'll add some CSS to style our form. This will create an appealing and responsive design.

```css
@import url(https://fonts.googleapis.com/css?family=Montserrat:400,700);

body { background: #1E1E1E; /* Dark background color */ }

header {
  text-align: center;
  padding: 20px;
  color: #fff;
}

h1 {
  margin: 0;
  font-size: 36px;
}

form { max-width: 420px; margin: 50px auto; }

.feedback-input {
  color: white;
  font-family: Helvetica, Arial, sans-serif;
  font-weight: 500;
  font-size: 18px;
  border-radius: 5px;
  line-height: 22px;
  background-color: transparent;
  border: 2px solid #7c7c7c; /* Dark gray color for borders */
  transition: all 0.3s;
  padding: 13px;
  margin-bottom: 15px;
  width: 100%;
  box-sizing: border-box;
  outline: 0;
}

.feedback-input:focus { border: 2px solid #555; /* Slightly lighter gray color on focus */ }

textarea {
  height: 150px;
  line-height: 150%;
  resize: vertical;
}

[type="submit"] {
  font-family: 'Montserrat', Arial, Helvetica, sans-serif;
  width: 100%;
  background: #555; /* Dark gray color for the button background */
  border-radius: 5px;
  border: 0;
  cursor: pointer;
  color: white;
  font-size: 24px;
  padding-top: 10px;
  padding-bottom: 10px;
  transition: all 0.3s;
  margin-top: -4px;
  font-weight: 700;
}
[type="submit"]:hover { background: #777; /* Slightly lighter gray color on hover */ }

#responseMessage {
  border-radius: 5px;
  color: #fff;
  font-size: 20px;
  text-align: center;
  /* max-width: 200px; */
  margin-left: auto;
  margin-right: auto;
}

#responseMessage.success {
  color: #008000; /* Green background for success */
}

#responseMessage.error {
  color: #FF0000; /* Red background for errors */
}

#responseMessage.show {
  opacity: 1;
}

footer {
  color: #fff;
  text-align: center;
  padding-bottom: 20px;
  position: fixed;
  bottom: 0;
  width: 100%;
}

footer p {
  margin: 0;
  font-size: 14px;
}
```

## JavaScript Functionality

Finally, the JavaScript code handles form submissions using the Fetch API to communicate with the backend.

```javascript
document.addEventListener("DOMContentLoaded", function () {
    const contactForm = document.getElementById("contactForm");
    const responseMessage = document.getElementById("responseMessage");

    contactForm.addEventListener("submit", function (event) {
        event.preventDefault();

        const name = document.getElementById('name').value;
        const email = document.getElementById('email').value;
        const message = document.getElementById('message').value;

        // const formData = new FormData(contactForm);
        const formData = {
            name: name,
            email: email,
            message: message,
        };

        const apiEndpoint = "https://localhost:3000/api/contact";

        fetch(apiEndpoint, {
            method: "POST",
            headers: {
                'Content-Type':
                    'application/json;charset=utf-8'
            },
            body: JSON.stringify(formData)
        })
            .then(response => response.json())
            .then(data => {
                responseMessage.innerHTML = `<p>${data.message}</p>`;
                responseMessage.classList.add("success", "show"); // Add 'show' class to make the message visible

                setTimeout(() => {
                    contactForm.reset();
                    responseMessage.innerHTML = "";
                    responseMessage.classList.remove("success", "show");
                }, 2000);
            })
            .catch(error => {
                console.error("Error:", error);
                responseMessage.innerHTML = `<p>Error submitting the form. Please try again later.</p>`;
                responseMessage.classList.add("error", "show"); // Add 'show' class to make the message visible

                setTimeout(() => {
                    responseMessage.innerHTML = "";
                    responseMessage.classList.remove("error", "show");
                }, 3000);
            });
    });
});
```

## Conclusion

By following these steps, you can create a functional and visually appealing contact form for your website. Remember to replace the API endpoint with your own backend URL to handle form submissions. Feel free to customize the styles and add more features based on your specific requirements.

## Exploring the Code

Visit the [GitHub repository](https://github.com/manthanank/contact) to explore the code in detail.

---

Feel free to customize the blog according to your preferences and provide more details or explanations where needed.