본문으로 건너뛰기

sendEmail Function Guide

JavaScript sendEmail Function

The sendEmail function implements the email sending feature when the 'SEND EMAIL' button on the web page is clicked.

It composes an email containing the user-entered name, email, and message values.


How It Works

  1. Get Button Object:

    Use document.getElementById('send-button') to retrieve the DOM object corresponding to the 'SEND EMAIL' button.

  2. Add Event Listener:

    Define the function to be executed on button click using button.addEventListener('click', function (e) {...}).

  3. Prevent Default Action:

    e.preventDefault() prevents the default action (such as form submission) that occurs on button click. This ensures that only the desired actions in JavaScript are performed.

  4. Retrieve Input Values:

    Retrieve the values of each input field (input-name, input-email, input-message) using JavaScript.

  5. Compose Email Content:

    Use the subject and body variables to compose the email's subject and body.

  6. Send Email:

    Use window.location.href with the 'mailto:' protocol to compose an email using the default email client.


Code Explanation

function sendEmail() {
// Retrieve the DOM object of the 'SEND EMAIL' button.
const button = document.getElementById('send-button');

// Add an event listener to be executed on button click.
button.addEventListener('click', function (e) {
// Prevent the default action on button click.
e.preventDefault();

// Retrieve user input values.
const name = document.getElementById('input-name').value;
const email = document.getElementById('input-email').value;
const message = document.getElementById('input-message').value;

// Compose the subject and body of the email.
const subject = 'Contact Information';
const body = `Name: ${name}\nEmail: ${email}\nMessage: ${message}`;

// Open a window to compose the email via the mail client.
window.location.href = `mailto:recipient@example.com?subject=${subject}&body=${body}`;
});
}