CMS Development

Woodsy
Top Contributor

Blog Search Limit Displayed Results Per Page

SOLVE

Hi, I have created a blog search that replaces the current blog list with searched blogs based on keyword. Currently the initial search displays 10 results. Is there a way to limit this within my code to show just 9 per page?
Input field code:

 

 

 

<!--  SEARCH START  -->       
<div class="hs-search-field"> 
<div class="hs-search-field__bar">
<form action="{{ 'https://www.360insights.com/blog' }}">
<label for="term">Search Blog</label>
<input type="text" class="hs-search-field__input" name="term" autocomplete="off" aria-label="Field Label | Search" placeholder="Search Blog">
<input type="hidden" name="type" value="BLOG_POST">
<input type="hidden" name="type" value="LISTING_PAGE">
<input type="hidden" name="is_search_results" value="true">
</form>
</div>
<ul class="hs-search-field__suggestions"></ul>
</div>
<!--  SEARCH END  -->  

 

 

 

Blog search results code:

 

 

 

<!--  BLOG SEARCH RESULTS START -->
<div class="hs-search-results">
  <template class="hs-search-results__template">
   <a href="#" class="hs-search-results__link card">
      
        <div class="hs-search-results__featured-image card__image">
          <img src="">
        </div>
      
      <div class="card__details">
      <div class="hs-search-results__title card__title">Content Title</div>
      <p style="display:none;" class="hs-search-results__description card__desc">Description</p>
        <span class="button button--arrow button--notext"></span>
      </div>
   </a>
  </template>
  
  <section class="blog-listing blog">
    <div class="content-wrapper">
      <div class="blog-listing__listings">
        <div id="hsresults" class="hs-search-results__listing cards cards--3"></div>
      </div>
    </div>
  </section>
  
  <div class="hs-search-results__pagination blog-listing__pagination" data-search-path="{{ site_settings.content_search_results_page_path }}">
    <a href="" class="hs-search-results__prev-page"></a>
    <a href="" class="hs-search-results__next-page"></a>
  </div>
</div>
<!--  BLOG SEARCH RESULTS END -->

 

 

 


Blog search Javascript;

 

 

 

<!--  SEARCH RESULTS SCRIPT START -->
<script>
var hsResultsPage = function(_resultsClass) {
  function buildResultsPage(_instance) {
    var resultTemplate = _instance.querySelector(
      '.hs-search-results__template'
    );
    var resultsSection = _instance.querySelector('.hs-search-results__listing');
    var searchPath = _instance
      .querySelector('.hs-search-results__pagination')
      .getAttribute('data-search-path');
    var prevLink = _instance.querySelector('.hs-search-results__prev-page');
    var nextLink = _instance.querySelector('.hs-search-results__next-page');

    var searchParams = new URLSearchParams(window.location.search.slice(1));

    /**
     * v1 of the search input module uses the `q` param for the search query.
     * This check is a fallback for a mixed v0 of search results and v1 of search input.
     */

    if (searchParams.has('q')) {
      searchParams.set('term', searchParams.get('q'));
      searchParams.delete('q');
    }

    function getTerm() {
      return searchParams.get('term') || '';
    }
    function getOffset() {
      return parseInt(searchParams.get('offset')) || 0;
    }
    function getLimit() {
      return parseInt(searchParams.get('limit'));
    }
    function addResult(title, url, description, featuredImage) {
      var newResult = document.importNode(resultTemplate.content, true);
      function isFeaturedImageEnabled() {
        if (
          newResult.querySelector('.hs-search-results__featured-image > img')
        ) {
          return true;
        }
      }
      newResult.querySelector('.hs-search-results__title').innerHTML = title;
      newResult.querySelector('.hs-search-results__link').href = url;
      newResult.querySelector(
        '.hs-search-results__description'
      ).innerHTML = description;
      if (typeof featuredImage !== 'undefined' && isFeaturedImageEnabled()) {
        newResult.querySelector(
          '.hs-search-results__featured-image > img'
        ).src=featuredImage;
      }
      resultsSection.appendChild(newResult);
    }
    function fillResults(results) {
      results.results.forEach(function(result, i) {
        addResult(
          result.title,
          result.url,
          result.description,
          result.featuredImageUrl
        );
      });
    }
    function emptyPagination() {
      prevLink.innerHTML = '';
      nextLink.innerHTML = '';
    }
    function emptyResults(searchedTerm) {
      resultsSection.innerHTML =
        '<div class="hs-search__no-results"><p>Sorry. There are no results for "' +
        searchedTerm +
        '"</p>' +
        '<p>Try rewording your query, or browse through our site.</p></div>';
    }
    function setSearchBarDefault(searchedTerm) {
      var searchBars = document.querySelectorAll('.hs-search-field__input');
      Array.prototype.forEach.call(searchBars, function(el) {
        el.value = searchedTerm;
      });
    }
    function httpRequest(term, offset) {
      var SEARCH_URL = '/_hcms/search?';
      var requestUrl = SEARCH_URL + searchParams + '&analytics=true';
      var request = new XMLHttpRequest();

      request.open('GET', requestUrl, true);
      request.onload = function() {
        if (request.status >= 200 && request.status < 400) {
          var data = JSON.parse(request.responseText);
          setSearchBarDefault(data.searchTerm);
          if (data.total > 0) {
            fillResults(data);
            paginate(data);
          } else {
            emptyResults(data.searchTerm);
            emptyPagination();
          }
        } else {
          console.error('Server reached, error retrieving results.');
        }
      };
      request.onerror = function() {
        console.error('Could not reach the server.');
      };
      request.send();
    }
    function paginate(results) {
      var updatedLimit = getLimit() || results.limit;

      function hasPreviousPage() {
        return results.page > 0;
      }
      function hasNextPage() {
        return results.offset <= results.total - updatedLimit;
      }

      if (hasPreviousPage()) {
        var prevParams = new URLSearchParams(searchParams.toString());
        prevParams.set(
          'offset',
          results.page * updatedLimit - parseInt(updatedLimit)
        );
        prevLink.href = '/' + searchPath + '?' + prevParams;
        prevLink.innerHTML = '&lt; Previous page';
      } else {
        prevLink.parentNode.removeChild(prevLink);
      }

      if (hasNextPage()) {
        var nextParams = new URLSearchParams(searchParams.toString());
        nextParams.set(
          'offset',
          results.page * updatedLimit + parseInt(updatedLimit)
        );
        nextLink.href = '/' + searchPath + '?' + nextParams;
        nextLink.innerHTML = 'Next page &gt;';
      } else {
        nextLink.parentNode.removeChild(nextLink);
      }
    }
    var getResults = (function() {
      if (getTerm()) {
        httpRequest(getTerm(), getOffset());
      } else {
        emptyPagination();
      }
    })();
  }
  (function() {
    var searchResults = document.querySelectorAll(_resultsClass);
    Array.prototype.forEach.call(searchResults, function(el) {
      buildResultsPage(el);
    });
  })();
};

if (
  document.attachEvent
    ? document.readyState === 'complete'
    : document.readyState !== 'loading'
) {
  var resultsPages = hsResultsPage('div.hs-search-results');
} else {
  document.addEventListener('DOMContentLoaded', function() {
    var resultsPages = hsResultsPage('div.hs-search-results');
  });
}
</script>
<!--  SEARCH RESULTS SCRIPT END -->

 

 

 


When the 10 results are displayed within the blog listing the next and previous pagination opens the system search results page with the next list of page results. Is there a way to stop the next pagination from opening the system search results page and instead just replace the blog listing? In effect staying on the blog listing page and just reloading it with the next set of results.

I assum I need to change this code to stop it from loading the system search results page but I'm not sure what to change it to.

 

 

 

<div class="hs-search-results__pagination blog-listing__pagination" data-search-path="{{ site_settings.content_search_results_page_path }}">

 

 

 

Thanks

0 Upvotes
1 Accepted solution
BarryGrennan
Solution
Top Contributor

Blog Search Limit Displayed Results Per Page

SOLVE

Add this to your search form

<input type="hidden" name="limit" value="9">

 


profile2022aBarry Grennan

Freelance HubSpot CMS Developer

Website | Contact | LinkedIn

 

 

View solution in original post

3 Replies 3
BarryGrennan
Solution
Top Contributor

Blog Search Limit Displayed Results Per Page

SOLVE

Add this to your search form

<input type="hidden" name="limit" value="9">

 


profile2022aBarry Grennan

Freelance HubSpot CMS Developer

Website | Contact | LinkedIn

 

 

Woodsy
Top Contributor

Blog Search Limit Displayed Results Per Page

SOLVE

Hi Barry, thank you.

 

Do you know how I would be able to adapt the next and back so that it would stay within the page and cycle through the results rather than the current next and back that push to the systems site results page?

Thanks

0 Upvotes
BarryGrennan
Top Contributor

Blog Search Limit Displayed Results Per Page

SOLVE

Not off the top of my head, but you'd need to edit the javascript of the custom search results module I advised you to create in the other thread

 


profile2022aBarry Grennan

Freelance HubSpot CMS Developer

Website | Contact | LinkedIn

 

 

0 Upvotes