Categories
CSS HTML JavaScript

Creating a Contact Email Form with HTML, CSS, and JavaScript: A Comprehensive Guide for Improved Accessibility and SEO

Contact forms are an essential component of any website, providing a quick and easy way for visitors to get in touch with website owners. This article will cover the steps required to create a contact form using HTML, CSS, and JavaScript. We will also discuss the importance of accessibility and how to ensure that the form is accessible to everyone.

Step 1: Create the HTML Form

The first step in creating a contact form is to create the HTML form. This can be done using the <form> element, which is used to create a container for a form. You can add various form elements within the form element, such as text inputs, text areas, checkboxes, and radio buttons. Here is an example of a basic HTML form:

<form action="#" method="post">
    <label for="name">Name:</label>
    <input type="text" id="name" name="name" required>

    <label for="email">Email:</label>
    <input type="email" id="email" name="email" required>

    <label for="message">Message:</label>
    <textarea id="message" name="message" required></textarea>

    <input type="submit" value="Send">
</form>

In the above example, we have created a basic contact form with three form elements: a text input for the name, an email input for the email address, and a text area for the message. We have also added a submit button to allow visitors to send the form.

Note that each form element has a unique ID and name attribute. The ID attribute is used to identify the form element in CSS and JavaScript, while the name attribute is used to identify the form element when the form is submitted.

Step 2: Style the Form with CSS

Once you have created the HTML form, the next step is to style it using CSS. This can be done using the various CSS properties available, such as font-size, color, background-color, border, and padding.

Here is an example of some essential CSS to style the contact form:

form {
    width: 400px;
    margin: 0 auto;
    font-size: 16px;
    line-height: 1.5;
}

label {
    display: block;
    margin-bottom: 5px;
}

input[type="text"],
input[type="email"],
textarea {
    width: 100%;
    padding: 10px;
    border: 1px solid #ccc;
    border-radius: 5px;
    font-size: 16px;
    line-height: 1.5;
    margin-bottom: 15px;
}

input[type="submit"] {
    background-color: #4CAF50;
    color: white;
    padding: 10px 20px;
    border: none;
    border-radius: 5px;
    font-size: 16px;
    cursor: pointer;
}

input[type="submit"]:hover {
    background-color: #3e8e41;
}

In the above example, we have set the width of the form to 400px and centred it using the margin property. We have also set the font-size and line-height properties to make the text more legible.

We have set the width to 100% for the form elements to ensure that they fill the entire width of the form container. We have also added some padding and a border to make the form elements more visually appealing.

Finally, we have styled the submit button with a background colour, padding, border radius, and font size. We have also added a hover effect to change the background colour when the mouse hovers over the button.

Step 3: Add JavaScript Validation

The next step in creating a contact form is to add JavaScript validation to ensure the form is filled out correctly before submitting it. This can help prevent errors and improve the user experience.

JavaScript validation can be added using the onsubmit event handler, which is triggered when the form is submitted. The onsubmit event handler can be used to check that all required form fields have been filled out correctly.

Here is an example of some basic JavaScript validation code:

function validateForm() {
    var name = document.forms["contactForm"]["name"].value;
    var email = document.forms["contactForm"]["email"].value;
    var message = document.forms["contactForm"]["message"].value;
    var error = "";

    if (name == "") {
        error += "Please enter your name.\n";
    }

    if (email == "") {
        error += "Please enter your email address.\n";
    } else if (!validateEmail(email)) {
        error += "Please enter a valid email address.\n";
    }

    if (message == "") {
        error += "Please enter a message.\n";
    }

    if (error != "") {
        alert(error);
        return false;
    }
}

function validateEmail(email) {
    var re = /\S+@\S+\.\S+/;
    return re.test(email);
}

In the above example, we created a validateForm() function called when the form is submitted. The function retrieves the values of the name, email, and message fields and checks that they are not empty. An error message is added to the error variable if any fields are empty.

The function also checks that the email address is valid using the validateEmail() function. The validateEmail() function uses a regular expression to check that the email address has the correct format.

If there are any errors, an alert message is displayed, and the function returns false, preventing the form from being submitted. If there are no errors, the function returns true, allowing the form to be submitted.

Step 4: Add Server-Side Validation

JavaScript validation is helpful for improving the user experience, but it is not enough to ensure that the form is filled out correctly. Server-side validation is also required to prevent malicious attacks and ensure the form data is processed correctly.

Server-side validation can be added using a server-side scripting language like PHP, Ruby, or Python. The server-side script can be used to check that the form data is valid and send an email to the website owner with the form data.

Here is an example of some basic PHP code to process the form data:

<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $name = strip_tags(trim($_POST["name"]));
    $email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
    $message = strip_tags(trim($_POST["message"]));

    if (empty($name) || empty($message) || !filter_var($email, FILTER_VALIDATE_EMAIL)) {
        http_response_code(400);
        echo "Please fill out all required fields and enter a valid email address.";
        exit;
    }

    $recipient = "youremail@example.com";
    $subject = "New Contact Form Submission";
    $email_content = "Name: $name\n";
    $email_content .= "Email: $email\n\n";
    $email_content .= "Message:\n$message\n";

    $headers = "From: $name <$email>";

    if (mail($recipient, $subject, $email_content, $headers)) {
        http_response_code(200);
        echo "Thank You! Your message has been sent.";
    } else {
        http_response_code(500);
      echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
       

In the above example, we have used the PHP $_POST superglobal to retrieve the values of the name, email, and message fields. We have then used PHP’s trim() function to remove any whitespace from the beginning and end of the values and PHP’s strip_tags() function to remove any HTML tags.

We have also used PHP’s filter_var() function to validate the email address and remove unwanted characters.

Next, we checked that all required fields have been filled out correctly. We return a 400 Bad Request status code and an error message if any errors are found.

If there are no errors, we have created a variable $recipient containing the email address of the website owner, a variable $subject containing the subject of the email, and a variable $email_content containing the message body.

We have also created a variable $headers containing the email headers, including the name and email address of the sender.

Finally, we have used PHP’s mail() function to send the email. If the email is sent successfully, we have returned a 200 OK status code and a success message. If the email fails to send, we return a 500 Internal Server Error status code and an error message.

Step 5: Test the Form

Once the form is complete, testing it to ensure it works correctly and thoroughly is essential. Here are some tests that you can perform:

  • Test the form validation by submitting the form with invalid or missing data. Ensure that the validation error messages are displayed correctly.
  • Test the form submission by submitting the form with valid data. Check that the email is sent successfully and that the correct success message is displayed.
  • Test the form accessibility by using a screen reader to navigate the form and ensure it is easy to use and understand.

Step 6: Add Accessibility Features

Accessibility is an important consideration when creating a contact form. Here are some tips for making your contact form more accessible:

  • Use semantic HTML elements to structure the form, such as <form>, <label>, and <input>. This helps screen readers and other assistive technologies to understand the structure of the form.
  • Use the for attribute on <label> elements to associate the label with the corresponding form field. This allows screen readers to announce the label when the form field is focused.
  • Use the title attribute to provide additional information about form fields. This can be useful for users who cannot see the form field or use a screen reader.
  • Use the required attribute on required form fields. This alerts users who cannot see the form visually that a field is required before they can submit the form.
  • Provide clear error messages when the form is submitted with invalid data. These messages should explain the nature of the error and suggest how the user can correct it.

Step 7: Optimize for SEO

Finally, optimizing your contact form for search engine optimization (SEO) is important. Here are some tips for doing so:

  • Use descriptive, keyword-rich text in the form field labels and the form itself. This can help improve the page’s relevance for the keywords you are targeting.
  • Use descriptive, keyword-rich text in the page title and meta description. This can help improve the click-through rate from search engine results pages.
  • Use schema.org markup to mark up the contact form with structured data. This can help search engines understand the purpose and structure of the form.
  • Ensure that the form is included in the site map and that the site map is submitted to search engines. This can help search engines discover and index the form more easily.
  • Use alt text on any images used in the form. This can help improve the relevance of the page for the keywords that you are targeting, as well as make the form more accessible to users who are unable to see the images.

Creating a Contact Email Form with HTML, CSS, and JavaScript

This article covers the steps involved in creating a contact form using HTML, CSS, and JavaScript. We have also discussed how to add accessibility features to the form and how to optimize it for SEO. By following these steps, you can create a contact form that is easy to use, accessible, and effective at capturing leads and communicating with your website visitors.