Livesearch

Livesearch is one of the most common features on websites. Imagine a website with thousands of records and no search feature. It would be incredibly frustrating, wouldn’t it? XD. So, here we’ll create a Livesearch feature using Briz.js + Leaf.js.

Example

<!-- dont forget to load briz.js and leaf.js library in your project via cdn link -->

<form data-ajax
  data-scope="formSearch"
  action="/partials/livesearch"
  method="get"
>
  <input data-action="input->search" type="text" name="search" placeholder="search here..." />
</form>

See the data-scope above? That’s a Leaf.js marker that says “this is the scope for formSearch.” Then, the data-action will execute the search function in the scope. After that, we’ll write it in a separate js file linked in the head tag.

//dont forget to import defineScope from Leaf.js cdn

defineScope("formSearch", ({ root, targets }) => {
  const input = targets.inputSearch
  let timeout
  
  function search() {
    clearTimeout(timeout)
    timeout = setTimeout(() => {
      root.requestSubmit()
    }, 500)
  }
  
  function disconnect() {
    clearTimeout(timeout)
  }
  
  return { search, disconnect }
})

When the user finishes typing, the system will call the search() function and send root.requestSubmit() (root is <form>, and requestSubmit() is the function to submit the form) to the server. and to disconnect will run automatically when <form> is removed from the DOM.

Demo

  • Hammer
  • Hamburger
  • Screwdriver
  • Sushi
  • Hand Saw
  • Pizza
  • Pliers
  • Pasta
  • Wrench
  • Tacos
  • Electric Drill
  • Steak
  • Hoe
  • Ramen
  • Shovel
  • Lasagna
  • Crowbar
  • Burrito
  • Chisel
  • Pancakes

Go back