การเพิ่มการโต้ตอบด้วย JavaScript
JavaScript (JS) คือภาษาโปรแกรมที่ใช้ในการเพิ่มการโต้ตอบ (Interactivity) ให้กับหน้าเว็บ ทำให้เว็บไซต์ไม่ใช่แค่เอกสารที่อยู่นิ่งๆ แต่สามารถตอบสนองต่อการกระทำของผู้ใช้ได้
3.1 พื้นฐาน JavaScript
การเรียกใช้ JavaScript
มี 3 วิธีหลักในการเรียกใช้โค้ด JS:
-
Inline: ใส่โค้ด JS ใน Attribute ของแท็ก HTML (ไม่แนะนำ)
<button onclick="alert('สวัสดี!')">คลิกฉัน</button> -
Internal: ใส่โค้ด JS ภายในแท็ก
<script>ในเอกสาร HTML<script> console.log("โค้ด JS ภายใน"); </script> -
External (วิธีที่แนะนำ): สร้างไฟล์
.jsแยกต่างหาก และเชื่อมโยงด้วยแท็ก<script>โดยนิยมวางไว้ก่อนแท็กปิด</body>เพื่อให้หน้าเว็บโหลดเร็วขึ้น<body> <!-- เนื้อหา HTML --> <script src="scripts/main.js"></script> </body>
ตัวแปร, ชนิดข้อมูล และ Operator
| แนวคิด | คำอธิบาย | ตัวอย่างโค้ด |
|---|---|---|
| ตัวแปร (Variable) | ใช้ let (สำหรับตัวแปรที่เปลี่ยนค่าได้) หรือ const (สำหรับค่าคงที่) |
const PI = 3.14;let name = "Manus"; |
| ชนิดข้อมูล (Data Types) | string, number, boolean, array, object |
let age = 30;let is_admin = true;let colors = ["red", "green"]; |
| Operator | ใช้ในการคำนวณและเปรียบเทียบ | +, -, *, /, == (เท่ากับ), === (เท่ากับและชนิดเดียวกัน), && (และ), || (หรือ) |
3.2 โครงสร้างควบคุม (Control Structures)
ใช้เพื่อควบคุมทิศทางการทำงานของโปรแกรม
เงื่อนไข (Conditionals)
ใช้ if, else if, else เพื่อตัดสินใจว่าจะรันโค้ดส่วนไหน
let score = 85;
if (score >= 80) {
console.log("ได้เกรด A");
} else if (score >= 70) {
console.log("ได้เกรด B");
} else {
console.log("ได้เกรด C หรือต่ำกว่า");
}ลูป (Loops)
ใช้ for หรือ while เพื่อทำซ้ำชุดคำสั่ง
// for loop
for (let i = 0; i < 5; i++) {
console.log("รอบที่ " + i);
}
// while loop
let count = 0;
while (count < 3) {
console.log("นับ: " + count);
count++;
}3.3 ฟังก์ชันและขอบเขต (Functions and Scope)
ฟังก์ชัน คือชุดคำสั่งที่ถูกรวมไว้เป็นกลุ่มและสามารถเรียกใช้งานซ้ำได้
การสร้างฟังก์ชัน
// Function Declaration
function greet(name) {
return "สวัสดี, " + name;
}
// Function Expression (ใช้บ่อยในยุคใหม่)
const calculateArea = function(width, height) {
return width * height;
};
// Arrow Function (รูปแบบย่อ)
const multiply = (a, b) => a * b;
console.log(greet("ผู้เรียน")); // Output: สวัสดี, ผู้เรียนขอบเขต (Scope)
Scope คือขอบเขตที่ตัวแปรสามารถเข้าถึงได้
| Scope | คำอธิบาย |
|---|---|
| Global Scope | ตัวแปรที่ประกาศนอกฟังก์ชัน สามารถเข้าถึงได้จากทุกที่ |
| Local/Function Scope | ตัวแปรที่ประกาศภายในฟังก์ชัน สามารถเข้าถึงได้เฉพาะในฟังก์ชันนั้น |
| Block Scope | ตัวแปรที่ประกาศด้วย let หรือ const ภายใน {} (เช่น if หรือ for) สามารถเข้าถึงได้เฉพาะใน Block นั้น |
3.4 การจัดการ DOM (Document Object Model)
DOM คือการแสดงโครงสร้างของเอกสาร HTML ในรูปแบบของ Object ทำให้ JavaScript สามารถเข้าถึงและจัดการ Element ต่างๆ บนหน้าเว็บได้
การเข้าถึง Element
| Method | คำอธิบาย |
|---|---|
document.getElementById('id') |
เลือก Element ที่มี ID ที่กำหนด |
document.querySelector('selector') |
เลือก Element แรกที่ตรงกับ CSS Selector |
document.querySelectorAll('selector') |
เลือกทุก Element ที่ตรงกับ CSS Selector (ได้เป็น NodeList) |
การจัดการ Element
// 1. เข้าถึง Element
const header = document.getElementById('main-header');
// 2. เปลี่ยนเนื้อหาข้อความ
header.textContent = "หัวข้อใหม่โดย JS";
// 3. เปลี่ยน Style
header.style.color = "blue";
header.style.backgroundColor = "yellow";
// 4. เพิ่ม Class
header.classList.add('active');
// 5. สร้าง Element ใหม่
const newParagraph = document.createElement('p');
newParagraph.textContent = "ย่อหน้าที่สร้างใหม่";
// 6. เพิ่ม Element ใหม่เข้าไปใน Body
document.body.appendChild(newParagraph);3.5 การจัดการเหตุการณ์ (Event Handling)
Event คือการกระทำที่เกิดขึ้นกับ Element (เช่น การคลิก, การพิมพ์, การโหลดหน้าเว็บ) JavaScript ใช้ Event Handler เพื่อตอบสนองต่อเหตุการณ์เหล่านี้
const myButton = document.getElementById('my-button');
// วิธีที่ 1: การกำหนด Event Handler
myButton.onclick = function() {
alert("คุณคลิกปุ่มแล้ว!");
};
// วิธีที่ 2: การใช้ addEventListener (วิธีที่แนะนำ)
myButton.addEventListener('click', function() {
console.log("ปุ่มถูกคลิก!");
myButton.textContent = "คลิกแล้ว!";
});3.6 การตรวจสอบความถูกต้องของฟอร์ม (Form Validation)
JS ใช้ในการตรวจสอบข้อมูลที่ผู้ใช้กรอกในฟอร์มก่อนที่จะส่งไปยังเซิร์ฟเวอร์ เพื่อลดภาระของเซิร์ฟเวอร์และเพิ่มประสบการณ์ผู้ใช้
const loginForm = document.getElementById('login-form');
loginForm.addEventListener('submit', function(event) {
// ป้องกันไม่ให้ฟอร์มส่งข้อมูลตามปกติ
event.preventDefault();
const username = document.getElementById('username').value;
const password = document.getElementById('password').value;
if (username.length < 5) {
alert("ชื่อผู้ใช้ต้องมีอย่างน้อย 5 ตัวอักษร");
return; // หยุดการทำงาน
}
if (password.length < 8) {
alert("รหัสผ่านต้องมีอย่างน้อย 8 ตัวอักษร");
return;
}
// ถ้าผ่านการตรวจสอบทั้งหมด ให้ส่งฟอร์ม
loginForm.submit();
});3.7 การสื่อสารกับเซิร์ฟเวอร์ด้วย AJAX/Fetch API
AJAX (Asynchronous JavaScript and XML) คือเทคนิคที่ช่วยให้ JS สามารถแลกเปลี่ยนข้อมูลกับเซิร์ฟเวอร์ได้โดยไม่ต้องโหลดหน้าเว็บใหม่ทั้งหมด ปัจจุบันนิยมใช้ Fetch API แทน
แนวคิด Asynchronous
การทำงานแบบ Asynchronous คือการที่โค้ดบางส่วนสามารถทำงานในพื้นหลังได้ โดยไม่บล็อกการทำงานของโค้ดส่วนอื่น ทำให้หน้าเว็บยังคงตอบสนองได้ (เช่น การดึงข้อมูลจาก API)
การใช้ Fetch API
ใช้เพื่อส่ง Request ไปยัง Server และรับ Response กลับมา
const apiUrl = 'https://jsonplaceholder.typicode.com/posts/1';
fetch(apiUrl)
.then(response => {
// ตรวจสอบว่า Response เป็น OK หรือไม่
if (!response.ok) {
throw new Error('Network response was not ok');
}
// แปลง Response เป็น JSON
return response.json();
})
.then(data => {
// จัดการกับข้อมูลที่ได้รับ
console.log("ข้อมูลที่ได้รับ:", data);
document.getElementById('post-title').textContent = data.title;
})
.catch(error => {
// จัดการกับข้อผิดพลาด
console.error('เกิดข้อผิดพลาดในการดึงข้อมูล:', error);
});แบบฝึกหัดท้ายบท
- สร้างปุ่มใน HTML และใช้
addEventListenerเพื่อให้เมื่อคลิกแล้ว ข้อความใน<h1>เปลี่ยนเป็น "JavaScript ทำงานแล้ว!" - สร้างฟังก์ชันที่รับตัวเลข 2 ตัว แล้วคืนค่าผลรวมของตัวเลขนั้น
- ใช้
document.querySelectorเลือก Element ที่มี Class ชื่อdata-displayแล้วเปลี่ยนสีพื้นหลังเป็นสีเหลือง - สร้างฟอร์มที่มีช่องกรอกอีเมล และใช้ JS ตรวจสอบว่ามี
@อยู่ในอีเมลหรือไม่ก่อนที่จะอนุญาตให้ส่งฟอร์ม
ในบทถัดไป เราจะเข้าสู่โลกของ Backend ด้วย PHP และ MySQL
ตัวอย่างโค้ดแบบฝึกหัดท้ายบท (JavaScript)
ไฟล์ index.html (สำหรับใช้กับแบบฝึกหัด):
<!DOCTYPE html>
<html lang="th">
<head>
<meta charset="UTF-8">
<title>แบบฝึกหัด JavaScript</title>
</head>
<body>
<h1 id="main-title">หัวข้อเริ่มต้น</h1>
<!-- ข้อ 1: ปุ่มสำหรับ Event Listener -->
<button id="change-text-button">คลิกเพื่อเปลี่ยนข้อความ</button>
<hr>
<!-- ข้อ 3: Element สำหรับ Query Selector -->
<div class="data-display">
กล่องนี้จะเปลี่ยนสีพื้นหลัง
</div>
<hr>
<!-- ข้อ 4: ฟอร์มสำหรับ Form Validation -->
<form id="email-form">
<label for="email">อีเมล:</label>
<input type="text" id="email" name="email" required>
<button type="submit">ส่งข้อมูล</button>
</form>
<!-- เชื่อมโยงไฟล์ JavaScript -->
<script src="main.js"></script>
</body>
</html>ไฟล์ main.js (สำหรับใช้กับแบบฝึกหัด):
// ข้อ 1: Event Listener
const button = document.getElementById('change-text-button');
const title = document.getElementById('main-title');
button.addEventListener('click', function() {
title.textContent = "JavaScript ทำงานแล้ว!";
console.log("ข้อความถูกเปลี่ยนแล้ว");
});
// ข้อ 2: ฟังก์ชันที่รับตัวเลข 2 ตัว แล้วคืนค่าผลรวม
function sumNumbers(num1, num2) {
return num1 + num2;
}
const result = sumNumbers(15, 25);
console.log("ผลรวมของ 15 และ 25 คือ:", result); // Output: 40
// ข้อ 3: document.querySelector และเปลี่ยน Style
const dataDisplay = document.querySelector('.data-display');
if (dataDisplay) {
dataDisplay.style.backgroundColor = "yellow";
dataDisplay.style.padding = "10px";
dataDisplay.textContent = "สีพื้นหลังเปลี่ยนเป็นสีเหลืองแล้ว";
}
// ข้อ 4: Form Validation
const emailForm = document.getElementById('email-form');
emailForm.addEventListener('submit', function(event) {
// ป้องกันไม่ให้ฟอร์มส่งข้อมูลตามปกติ
event.preventDefault();
const emailInput = document.getElementById('email');
const emailValue = emailInput.value;
if (emailValue.includes('@')) {
alert("อีเมลถูกต้อง! กำลังส่งข้อมูล...");
// ในสถานการณ์จริง จะทำการส่งฟอร์ม: emailForm.submit();
} else {
alert("กรุณากรอกอีเมลให้ถูกต้อง (ต้องมีเครื่องหมาย @)");
emailInput.focus(); // ให้ Cursor ไปอยู่ที่ช่องกรอกอีเมล
}
});