หัวข้อ 6: Attribute พิเศษ

แนวคิดหลัก

Attribute ช่วยเพิ่มข้อมูลหรือพฤติกรรมให้ element บาง attribute ใช้สำหรับเลือก element ด้วย CSS/JavaScript บาง attribute ใช้เก็บข้อมูล และบาง attribute ช่วยให้ผู้ใช้ที่ใช้ assistive technology เข้าถึงเว็บได้ดีขึ้น

id

id เป็นตัวระบุเฉพาะต่อหน้า ไม่ควรซ้ำกันในเอกสารเดียวกัน ใช้กับ CSS, JavaScript และ anchor link ได้

<section id="overview">
  <h2>ภาพรวม</h2>
</section>

CSS:

#overview {
  padding: 20px;
}

JavaScript:

const overview = document.getElementById("overview");

class

class เป็นตัวระบุที่ใช้ซ้ำได้ เหมาะกับการจัดกลุ่ม style หรือเลือก element หลายตัว

<article class="course-card featured">
  <h2>HTML</h2>
</article>

CSS:

.course-card {
  border: 1px solid #ddd;
}

data-*

data-* เป็น custom attribute สำหรับเก็บข้อมูลใน HTML โดยไม่ทำให้ HTML ผิดมาตรฐาน

<button data-id="5" data-action="delete">ลบรายการ</button>

JavaScript:

const button = document.querySelector("button");
console.log(button.dataset.id);
console.log(button.dataset.action);

เหมาะกับการเก็บ id, state หรือข้อมูลเล็ก ๆ ที่ JavaScript ต้องใช้อ่านจาก element

ARIA Attributes

ARIA ช่วยเพิ่ม accessibility เมื่อ semantic HTML เพียงอย่างเดียวไม่พอ

aria-label

ใช้กำหนดชื่อที่ screen reader อ่าน

<button aria-label="ปิดหน้าต่าง">X</button>

aria-hidden

ใช้ซ่อน element จาก assistive technology

<span aria-hidden="true"></span>

aria-expanded

ใช้บอกสถานะเปิด/ปิดของ UI เช่น dropdown หรือ accordion

<button aria-expanded="false" aria-controls="menu">เมนู</button>
<nav id="menu">...</nav>

tabindex

tabindex ใช้กำหนดลำดับการ focus ด้วยแป้น Tab

<button tabindex="0">ปุ่มปกติ</button>
<div tabindex="0">กล่องที่ focus ได้</div>

แนวทางที่ดี:

  1. ใช้ tabindex="0" เพื่อให้ element เข้า flow การ tab ตามธรรมชาติ
  2. หลีกเลี่ยง tabindex ค่าบวก เพราะทำให้ลำดับ focus สับสน
  3. ใช้ tabindex="-1" เมื่อต้องการให้ focus ด้วย JavaScript แต่ไม่อยู่ในลำดับ Tab ปกติ

เปรียบเทียบ id และ class

Attribute ใช้ซ้ำได้ไหม ใช้กับ
id ไม่ควรซ้ำ element เฉพาะตัว, anchor, JS
class ใช้ซ้ำได้ style หลาย element, grouping

กิจกรรม

สร้างรายการบทเรียน 5 รายการ โดยแต่ละรายการมี class="lesson-card" และ data-id ต่างกัน จากนั้นเพิ่มปุ่ม dropdown ที่มี aria-expanded

แบบทดสอบหลังเรียน

  1. id ควรซ้ำกันในหน้าเดียวกันหรือไม่ เพราะอะไร
  2. class เหมาะกับงานแบบใด
  3. data-* ใช้เก็บข้อมูลประเภทใด
  4. aria-label ช่วยผู้ใช้กลุ่มใด
  5. เหตุใดควรระวังการใช้ tabindex ค่าบวก

กลับสัปดาห์ที่ 2