Categories
Programming

Creating a Javascript load more plugin part 2 – Searching2 min read

In the first part Creating a Javascript load more plugin part 1 , we have created a javascript plugin which loads data from an API page. Let’s build upon on it.

Today we are going to add search option to our plugin, children ? .

Objectives ?

  • Add search bar to the page.
  • On input on search bar, load in relevant content from the API.
  • The API should take in a search parameter and provide relevant results.

As of now we are sending two parameters to the API – start and count. We would add one more q for sending the search query.

For learning how add searching option at the server end, please refer this tutorial from Codecourse – Basic PHP & MySQL Searching.

It uses PHP and MYSQL but you get the idea ? .

Demo page – Javascript load more plugin – search added.

We have to add one more line to our previous HTML code to include the search bar.

<input type="search" autocomplete="off" class="finder" />

We can add this anywhere inside our main container. Only condition is that it should have a class of finder, so that our plugin can identify it.

For styling HTML forms and form elements view this tutorial – Styling HTML Forms .

Updating the Plugin

Now let’s upgrade our plugin. First we would find the search bar.

//Search bar
this.finder = this.elem.getElementsByClassName('finder').length ? this.elem.getElementsByClassName('finder')[0] : false;

If you are not able to follow, please go through part one of this series.

Now, inside our lmore.load method we would append the search term to the GET query string.

//create query string with
//start and count variables
var qs = this.source + '?lmore_start=' + this.start + '&lmore_count=' + this.count;

//Send search query if search bar is available
qs += this.finder ? '&q=' + this.finder.value.trim() : '';
this.http.open('GET', qs);
this.http.send();

Let’s add and event listener to the search bar so that, data can be loaded while searching.

We could load data on any event, but I prefer the on-input event because it gives an instant search effect.

I don’t like search bars that have a button which has to be clicked to search. We are in 2016, common guys ( who make me click a button to search ? )  ?.

We could even pass the event, as input for the plugin.

if (this.finder) {
  this.finder.addEventListener('input', function() {
    this.load();
  }.bind(this));
}

You could also use this plugin to give search suggestions like google. Maybe we could use the plugin two times, one for suggestions and one for showing search results.

Comment below if you want to see this plugin give you search suggestions.

Leave a Reply

Your email address will not be published. Required fields are marked *