JavaScript sendEmail
Function
The sendEmail function is designed to implement the email sending feature when the 'SEND EMAIL' button on the web page is clicked.
It prepares an email that includes the user's input of name, email, and message.
Operation Method
-
Get the Button Object:
Use
document.getElementById('send-button')
to get the DOM object corresponding to the 'SEND EMAIL' button. -
Add Event Listener:
Define the function to be executed upon the button click by using
button.addEventListener('click', function (e) {...})
. -
Prevent Default Behavior:
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. -
Get Input Values:
Obtain the values of each input field (
input-name
,input-email
,input-message
) using JavaScript. -
Compose Email Content:
Use the
subject
andbody
variables to compose the email's subject and body. -
Send Email:
Use
window.location.href
with the 'mailto:' protocol to open the default email client with the prepared email.
Code Explanation
function sendEmail() {
// Get the DOM object of the 'SEND EMAIL' button.
const button = document.getElementById('send-button');
// Add an event listener that will be executed upon button click.
button.addEventListener('click', function (e) {
// Prevent the default action on button click.
e.preventDefault();
// Retrieve the user's 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 the default email client with the prepared email.
window.location.href = `mailto:recipient@example.com?subject=${subject}&body=${body}`;
});
}
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.