Widget mục lục tự động cho heading H2 trên Blogger

Với các bài viết dài chia thành nhiều phần rõ ràng, việc hiển thị danh sách heading H2 trên widget ở thanh bên giúp người đọc nắm nhanh cấu trúc nội dung và chuyển thẳng tới mục quan tâm chỉ với một cú click.

Giải pháp dưới đây sử dụng thuần HTML + CSS + Vanilla JS, không phụ thuộc thư viện ngoài, có thể dán trực tiếp vào Bố cục (Layout) -> Thêm tiện ích (Add a Gadget) -> HTML/JavaScript trên Blogger.

1. Code Widget (Dán vào tiện ích HTML/JavaScript)

Bạn sao chép toàn bộ đoạn mã bên dưới và dán vào phần nội dung của tiện ích HTML/JavaScript trong trang quản trị Blogger:

<style>
  #toc-sidebar-widget {
    background: #ffffff;
    border: 1px solid #e2e8f0;
    border-radius: 8px;
    padding: 16px;
    box-shadow: 0 2px 6px rgba(0, 0, 0, 0.04);
    font-family: inherit;
  }

  .toc-widget-title {
    font-size: 16px;
    font-weight: 700;
    margin: 0 0 12px 0;
    padding-bottom: 8px;
    border-bottom: 2px solid #f1f5f9;
    color: #1e293b;
  }

  #toc-h2-list {
    list-style: none;
    padding: 0;
    margin: 0;
  }

  #toc-h2-list li {
    margin-bottom: 8px;
    line-height: 1.45;
  }

  #toc-h2-list li:last-child {
    margin-bottom: 0;
  }

  #toc-h2-list a {
    text-decoration: none;
    color: #475569;
    font-size: 14px;
    display: block;
    padding: 5px 8px;
    border-left: 3px solid transparent;
    border-radius: 0 4px 4px 0;
    transition: all 0.2s ease;
  }

  #toc-h2-list a:hover {
    color: #0284c7;
    background-color: #f8fafc;
    border-left-color: #0284c7;
  }

  #toc-h2-list a.active {
    color: #0284c7;
    font-weight: 600;
    border-left-color: #0284c7;
    background-color: #f0f9ff;
  }
</style>

<div id="toc-sidebar-widget" style="display: none;">
  <div class="toc-widget-title">Mục lục (H2)</div>
  <ul id="toc-h2-list"></ul>
</div>

<script>
document.addEventListener("DOMContentLoaded", function () {
  const postBody = document.querySelector(".post-body, .entry-content, article");
  const tocWidget = document.getElementById("toc-sidebar-widget");
  const tocList = document.getElementById("toc-h2-list");

  if (!postBody || !tocWidget || !tocList) return;

  const headings = postBody.querySelectorAll("h2");

  // Chỉ hiển thị khi bài viết có ít nhất 2 thẻ H2
  if (headings.length < 2) return;

  tocWidget.style.display = "block";

  function createSlug(text) {
    return text
      .toString()
      .toLowerCase()
      .normalize("NFD")
      .replace(/[\u0300-\u036f]/g, "")
      .replace(/[đĐ]/g, "d")
      .replace(/[^a-z0-9\s-]/g, "")
      .trim()
      .replace(/\s+/g, "-");
  }

  const tocItems = [];

  headings.forEach(function (heading, index) {
    const label = heading.textContent.trim();
    if (!label) return;

    if (!heading.id) {
      const slug = createSlug(label) || "section";
      heading.id = slug + "-" + index;
    }

    const li = document.createElement("li");
    const link = document.createElement("a");
    link.href = "#" + heading.id;
    link.textContent = label;

    link.addEventListener("click", function (event) {
      event.preventDefault();
      const target = document.getElementById(heading.id);
      if (target) {
        const offsetTop = target.getBoundingClientRect().top + window.scrollY - 16;
        window.scrollTo({
          top: offsetTop,
          behavior: "smooth"
        });
      }
    });

    li.appendChild(link);
    tocList.appendChild(li);
    tocItems.push({ heading: heading, link: link });
  });

  if (tocItems.length < 2) {
    tocWidget.style.display = "none";
    return;
  }

  const observer = new IntersectionObserver(
    function (entries) {
      entries.forEach(function (entry) {
        if (entry.isIntersecting) {
          tocItems.forEach(function (item) {
            item.link.classList.remove("active");
          });
          const matched = tocItems.find(function (item) {
            return item.heading === entry.target;
          });
          if (matched) {
            matched.link.classList.add("active");
          }
        }
      });
    },
    {
      root: null,
      rootMargin: "0px 0px -75% 0px",
      threshold: 0
    }
  );

  tocItems.forEach(function (item) {
    observer.observe(item.heading);
  });
});
</script>

2. Cách hoạt động và điểm nổi bật

  • Tự động quét thẻ H2: Script tìm vùng nội dung bài viết (.post-body, .entry-content, hoặc article), lấy toàn bộ thẻ <h2> và dựng danh sách liên kết tương ứng.
  • Tự sinh id hỗ trợ tiếng Việt: Nếu thẻ <h2> chưa có thuộc tính id, hàm createSlug() sẽ chuẩn hóa tiếng Việt không dấu để tạo anchor hợp lệ.
  • Tự ẩn khi không cần thiết: Ở trang chủ, trang lưu trữ hoặc các bài ngắn có ít hơn 2 thẻ H2, widget giữ trạng thái display: none để không làm rối giao diện.
  • Đánh dấu mục đang đọc: IntersectionObserver tự động thêm class .active vào mục H2 tương ứng với vị trí cuộn hiện tại của người đọc.

3. Lưu ý khi áp dụng trên Blogger

  • Vùng chứa nội dung bài viết: Nếu template Blogger của bạn dùng class khác cho phần thân bài (ví dụ .post-content), chỉ cần bổ sung selector đó vào dòng document.querySelector(...).
  • Đặt tiêu đề nhất quán: Khi soạn bài trong trình soạn thảo của Blogger, hãy chọn Tiêu đề (Heading) (<h2>) cho các tiêu đề mục chính để widget nhận diện đầy đủ.

Nhận xét

Bài đăng phổ biến từ blog này

Kinh nghiệm tạo biểu đồ Use Case

PHÉP TOÁN XOR

Phần mềm hỗ trợ vẽ bản đồ tư duy trên máy tính

Power Designer 12.5