Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

result hits in multiple columns using Algolia and Bootstrap 3

I'm using Algolia instantsearch.js for search, and to display my result page, I'm using Bootstrap 3, and I'd like hits to be displayed in 3 columns:

qry | hit1 | hit2
    | hit3 | hit4
    | hit5 | hit6

(where qry = the search query input widget) etc..

If it's mobile, it should display as:

qry
hit1
hit2
hit3
etc.

Can someone help me with the html/css I can use to implement this? Thanks!

like image 267
Nathan W Avatar asked Jan 07 '23 23:01

Nathan W


1 Answers

Basically, you want to use bootstrap rows and grid layout col-{xs,sm,md,lg}-X (More info about the grid layout here).
One interesting property with bootstrap is that if you declare a block as being col-YY-X, if the screen width is under the dimensions YY is associated with, it automatically expands to the full width.
instantsearch.js's widgets expose a cssClasses parameter that allows you to customize the classes of the underlying markup.

To easily do two columns, all you need to do is declare the root element of the cssClasses as being a .row, and each result as a .col-sm-6 (or .col-md-6 or .col-lg-6 depending on which screen size you want it to apply).

By combining them, you can have some really interesting layouts.
See this JSFiddle

Here, I've extended a bit the idea. Try to resize the view, and you'll see that it automatically picks a number of results to display per line depending on the width by combining multiple col-YY-X classes on the hit widget.

search.addWidget(
  instantsearch.widgets.hits({
    container: '#hits',
    templates: {
      empty: 'No results',
      item: '<div class="hit">{{title}}</div>'
    },
    hitsPerPage: 6,
    cssClasses: {
      root: 'row',
      item: 'col-lg-3 col-md-4 col-sm-6'
    }
  })
);

As you can see, I've also added an inner class to the item template to be able to use the item as a wrapper with padding inside to avoid having the hits glued to each other. I apply the border to the inner element, because adding margins to bootstrap grid elements is not the right solution.

The layout itself is really simple, you can just nest rows together:

<div class="container-fluid">
  <div id="search" class="row">
    <div class="col-sm-4">
      <div id="input"></div>
    </div>
    <div class="col-sm-8">
      <div id="hits" class="row">
      </div>
    </div>
  </div>
</div>
like image 178
Jerska Avatar answered Jan 31 '23 10:01

Jerska