🔥🔥 HOT! 🔥🔥 Template siêu VIP #790K

Live search cho Blogspot

Zalo 0971539681 Tư vấn & Hỗ trợ

Chia sẻ code tìm kiếm Live search cho Blogspot theo từ khóa, từ khóa sẽ tìm theo tên và nội dung của bài viết. Hướng dẫn tạo live search cho Blogger. Trên mạng nhiều bài chia sẻ code live search cho blogspot thì chưa được tối ưu cho lắm, dưới đây có lẽ là 1 bản code hoàn hảo nhất có thể.


Demo Live search cho Blogspot trực tiếp trên Blog này của mình ở trang chủ như hình dưới


Live search cho Blogspot


Blog của mỗi người không ai giống ai cả, nên tùy vào blog mà áp dụng nếu nó phù hợp cho việc đặt code live search.


Giải thích qua HTML của khung tìm



<form action='/search' class='search-form' method='get'>

  <input id='searchInput' name='q' onkeyup='liveSearch()' placeholder='Live search...' type='text' />

</form>

<div id='resultContainer' />


Trong đó: 

id='searchInput' và onkeyup='liveSearch()' bạn hãy thêm nó vào khung input nhập trên blog của các bạn. Nếu khung search của bạn đã có ID rồi thì đổi tên ID vào code ở dưới code var searchKeyword = document.getElementById('searchInput').value;

<div id='resultContainer' /> là thẻ HTML để hiện thỉ kết quả tìm kiếm, bạn hãy thêm vào dưới khung input search trên blog của các bạn như bên trên.


Và đây là code, các bạn copy dán trước thẻ đóng </body> hoặc dán dưới khung search của các bạn đều được.


Lưu ý: CSS kèm theo mình chỉ code đẹp trên blog của mình, nó có thể không đẹp tren Blog của các bạn, các bạn tự Fix lấy cho nó tương thích.


<style>
/*<![CDATA[*/
#resultContainer{max-width:475px;margin:20px auto}
#resultContainer ul{list-style-type:none;padding:0}
#resultContainer li{margin-bottom:10px;padding:10px;border:1px solid #ddd;border-radius:5px;transition:background-color 0.3s;list-style:none;text-align:left}
#resultContainer li a{text-decoration:none;color:#fff;font-weight:bold;font-size:16px}
#resultContainer li:hover{background-color:#f5f5f5}
#resultContainer li a:hover{color:#1f06ec}
#resultContainer .noResults{font-weight:bold;font-size:18px;color:#777}
/*]]>*/
</style>      
<script>
  //<![CDATA[
  window.addEventListener('load', function() {
    var searchTimeout;
    window.liveSearch = function() {
      clearTimeout(searchTimeout);
      searchTimeout = setTimeout(function() {
        var searchKeyword = document.getElementById('searchInput').value;
        // Nếu searchKeyword rỗng, xóa kết quả và thoát khỏi hàm
        if (!searchKeyword.trim()) {
          clearResults();
          return;
        }
        // Gọi hàm Ajax để tải dữ liệu
        $.ajax({
          url: '/feeds/posts/default?q=' + encodeURIComponent(searchKeyword) + '&alt=json',
          type: 'GET',
          dataType: 'json',
          success: function(data) {
            displayResults(data, searchKeyword);
          },
          error: function(error) {
            console.error('Error fetching blog data:', error);
          }
        });
      }, 300); // Thời gian chờ 300ms sau khi ngừng nhập để tránh gọi Ajax liên tục
    }
    window.displayResults = function(data, searchKeyword) {
      var resultContainer = document.getElementById('resultContainer');
      resultContainer.innerHTML = ''; // Xóa nội dung cũ
      if (data.feed.entry) {
        // Lặp qua mỗi bài viết trong kết quả
        for (var i = 0; i < data.feed.entry.length; i++) {
          var entry = data.feed.entry[i];
          var title = entry.title.$t;
          var content = entry.content.$t;
          var link = entry.link.find(link => link.rel === 'alternate').href;
          // Kiểm tra xem tiêu đề hoặc nội dung có chứa từ khóa tìm kiếm không
          if (title.toLowerCase().includes(searchKeyword.toLowerCase()) || content.toLowerCase().includes(searchKeyword.toLowerCase())) {
            // Tạo một phần tử HTML để hiển thị kết quả
            var resultItem = document.createElement('li');
            resultItem.innerHTML = '<a href="' + link + '" target="_blank">' + title + '</a>';
            resultContainer.appendChild(resultItem);
          }
        }
      }
      if (resultContainer.children.length === 0) {
        resultContainer.innerHTML = '<li class="noResults">No results found.</li>';
      }
    }
    // Hàm xóa kết quả
    function clearResults() {
      var resultContainer = document.getElementById('resultContainer');
      resultContainer.innerHTML = '';
    }
  })
  //]]>
</script>

Bài liên quan ngẫu nhiên

Nhận xét

Contact Me on Zalo