My Contact List Project

my contact list

สวัสดีทุกคน บทความนี้ Matter Devs ได้นำ Project ด้วยภาษา HTML CSS JavaScript อีกแล้ว เป็นโปรเจคไว้บันทึกข้อมูลและแสดงออกมาเป็นตาราง สามารถเพิ่มและลบข้อมูล แถมยังมีการตรวจสอบ (Validation) และแจ้งเตือน (Alert) ขึ้นมากรณีไม่ป้อนข้อมูล ให้เพิ่มข้อมูลทุกช่อง เพิ่มข้อมูลแล้ว และลบข้อมูลแล้ว หากนึกภาพไม่ออกคลิกดู Demo ก่อนได้เลย^^

#2/∞ My Contact List (Responsive) Project

File ทั้งหมดก็จะมี index.html, style.css, script.js ดังรูปภาพทางซ้ายมือ ส่วนรูปภาพทุกคนสามารถนำมาจากเว็บแจกรูปภาพฟรี ที่ไม่มีลิขสิทธิ์ เช่น

Unsplash Pixabay Pexels

และเว็บอื่นๆอีกมากมาย

ส่วนธีมสวยๆ ไม่ต้องเขียนโค้ดให้ยุ่งยาก ใช้ธีมฟรีจาก Bootswatch เลือกได้ตามใจชอบได้เลย

Bootswatch

1. ไฟล์ index.html

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

<head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <link rel="stylesheet" href="https://bootswatch.com/5/sketchy/bootstrap.min.css" />
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.6.3/css/all.css" />
    <link rel="stylesheet" href="style.css">
    <title>MyContactList By Matter Devs</title>
</head>

<body>
    <div class="container mt-4">
        <h1 class="display-4 text-center">
            <i class="fas fa-address-book "></i>
            <span class="text-primary">My</span>Contact
            <span class="text-primary">List.<sub>by Matter Devs</sub></span>
        </h1>
        <form id="contact-form">
            <div class="form-group">
                <label for="username">Username</label>
                <input type="text" id="username" class="form-control">
            </div>
            <div class="form-group">
                <label for="company">Company</label>
                <input type="text" id="company" class="form-control">
            </div>
            <div class="form-group">
                <label for="telephone">Telephone</label>
                <input type="text" id="telephone" class="form-control">
            </div>
            <input type="submit" value="Add Contact" class="btn btn-primary btn-block">
        </form>
        <table class="table table-striped mt-5">
            <thead>
                <tr>
                    <th>Username</th>
                    <th>Company</th>
                    <th>Telephone</th>
                    <th></th>
                </tr>
            </thead>
            <tbody id="contact-list"></tbody>
        </table>
    </div>
    <script src="script.js"></script>
</body>

</html>

2. ไฟล์ style.css

body {
  margin: 0;
  background-image: linear-gradient(
      to bottom,
      rgba(255, 255, 255, 0.8) 0%,
      rgba(255, 255, 255, 0.9) 100%
    ),
    url("img/laptop\ pattern.jpg");
  background-size: cover;
  color: #f6c453;
  text-align: center;
}

.container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  flex-direction: column;
}

.form-group {
  margin-bottom: 15px;
  width: 250px;
}

sub {
  font-size: 12px;
}

3. ไฟล์ script.js

//Contact Class: Represents a Contact
class Contact {
  constructor(username, company, telephone) {
    this.username = username;
    this.company = company;
    this.telephone = telephone;
  }
}

//UI Class: Handle UI Tasks
class UI {
  static displayContacts() {
    const contacts = MyContact.getContacts();

    contacts.forEach((contact) => UI.addContactToList(contact));
  }

  static addContactToList(contact) {
    const list = document.querySelector("#contact-list");

    const row = document.createElement("tr");
    row.innerHTML = `
        <td>${contact.username}</td>
        <td>${contact.company}</td>
        <td>${contact.telephone}</td>
        <td><a href="#" class="btn btn-danger btn-sm delete">X</a></td>
        `;

    list.appendChild(row);
  }

  static deleteContact(el) {
    if (el.classList.contains("delete")) {
      el.parentElement.parentElement.remove();
    }
  }

  static showAlert(message, className) {
    const div = document.createElement("div");
    div.className = `alert alert-${className}`;
    div.appendChild(document.createTextNode(message));
    const container = document.querySelector(".container");
    const form = document.querySelector("#contact-form");
    container.insertBefore(div, form);

    // Vanish in 3 seconds
    setTimeout(() => document.querySelector(".alert").remove(), 5000);
  }

  static clearFields() {
    document.querySelector("#username").value = "";
    document.querySelector("#company").value = "";
    document.querySelector("#telephone").value = "";
  }
}

//MyContact Class: Handles Storage
class MyContact {
  static getContacts() {
    let contacts;
    if (localStorage.getItem("contacts") === null) {
      contacts = [];
    } else {
      contacts = JSON.parse(localStorage.getItem("contacts"));
    }
    return contacts;
  }

  static addContact(contact) {
    const contacts = MyContact.getContacts();
    contacts.push(contact);
    localStorage.setItem("contacts", JSON.stringify(contacts));
  }

  static removeContact(telephone) {
    const contacts = MyContact.getContacts();

    contacts.forEach((contact, index) => {
      if (contact.telephone === telephone) {
        contacts.splice(index, 1);
      }
    });

    localStorage.setItem("contacts", JSON.stringify(contacts));
  }
}
//Event: Display Contacts
document.addEventListener("DOMContentLoaded", UI.displayContacts);

//Event: Add a Contact
document.querySelector("#contact-form").addEventListener("submit", (e) => {
  //Prevent actual submit
  e.preventDefault();
  //Get form values
  const username = document.querySelector("#username").value;
  const company = document.querySelector("#company").value;
  const telephone = document.querySelector("#telephone").value;

  //Validate
  if (username === "" || company === "" || telephone === "") {
    UI.showAlert("Please fill in all fields", "danger");
  } else {
    //Instantiate contact
    const contact = new Contact(username, company, telephone);

    //Add Contact to UI
    UI.addContactToList(contact);

    //Add Contact to MyContact
    MyContact.addContact(contact);

    //Show success message
    UI.showAlert("Contact Added", "success");

    //Clear fields
    UI.clearFields();
  }
});

//Event: Remove a Contact
document.querySelector("#contact-list").addEventListener("click", (e) => {
  //Remove contact from UI
  UI.deleteContact(e.target);

  //Remove contact from stores
  MyContact.removeContact(
    e.target.parentElement.previousElementSibling.textContent
  );
  //Show success message
  UI.showAlert("Contact Removed", "success");
});

เป็นยังไงกันบ้างกับ Source Code ที่ Matter Devs ได้นำมาแจก ซึ่งเป็นระบบพื้นฐานที่ไม่ว่าจะเว็บไซต์หรือแอปพลิเคชันที่จะต้องมี นั่นก็คือ เพิ่ม ลบ แก้ไข และแสดงข้อมูล แต่โปรเจคนี้ขาดแก้ไข และเพิ่มข้อมูลในฐานข้อมูล ไว้โปรเจคต่อๆไปมีแน่นอน ฝากติดตามด้วยน๊าาา

ขอบคุณ Workshop จาก Traversy Media