@harsh_bhavsar
Kindly Follow these steps:
- create a predictive-search.liquid file
and paste this code.
{%- if predictive_search.performed -%}
{%- if predictive_search.resources.products.size > 0 -%}
##
{{ 'templates.search.products' | t }}
{%- endif -%}
{%- for product in predictive_search.resources.products -%}
- {%- if product.featured_media != blank -%}
{%- endif -%}
{%- if settings.predictive_search_show_vendor -%}
{{ 'accessibility.vendor' | t }}
{{ product.vendor }}
{%- endif -%}
### {{ product.title }}
{%- if settings.predictive_search_show_price -%}
{% render 'price', product: product, use_variant: true, show_badges: false %}
{%- endif -%}
{%- endfor -%}
-
{%- if search.results_count == 0 -%}
{{ 'templates.search.no_results' | t: terms: predictive_search.terms }}
{%- else -%}
{{ 'templates.search.results_with_count' | t: terms: predictive_search.terms, count: predictive_search.resources.products.size }}
{%- endif -%}
{%- endif -%}
- create file predictive-search.js and paste this code**.**
class PredictiveSearch extends HTMLElement {
constructor() {
super();
this.cachedResults = {};
this.input = this.querySelector('input[type="search"]');
this.predictiveSearchResults = this.querySelector('[data-predictive-search]');
this.setupEventListeners();
}
setupEventListeners() {
const form = this.querySelector('form.search');
form.addEventListener('submit', this.onFormSubmit.bind(this));
this.input.addEventListener('input', debounce((event) => {
this.onChange(event);
}, 300).bind(this));
this.input.addEventListener('focus', this.onFocus.bind(this));
this.addEventListener('focusout', this.onFocusOut.bind(this));
this.addEventListener('keyup', this.onKeyup.bind(this));
this.addEventListener('keydown', this.onKeydown.bind(this));
}
getQuery() {
return this.input.value.trim();
}
onChange() {
const searchTerm = this.getQuery();
if (!searchTerm.length) {
this.close(true);
return;
}
this.getSearchResults(searchTerm);
}
onFormSubmit(event) {
if (!this.getQuery().length || this.querySelector('[aria-selected="true"] a')) event.preventDefault();
}
onFocus() {
const searchTerm = this.getQuery();
if (!searchTerm.length) return;
if (this.getAttribute('results') === 'true') {
this.open();
} else {
this.getSearchResults(searchTerm);
}
}
onFocusOut() {
setTimeout(() => {
if (!this.contains(document.activeElement)) this.close();
})
}
onKeyup(event) {
if (!this.getQuery().length) this.close(true);
event.preventDefault();
switch (event.code) {
case 'ArrowUp':
this.switchOption('up')
break;
case 'ArrowDown':
this.switchOption('down');
break;
case 'Enter':
this.selectOption();
break;
}
}
onKeydown(event) {
// Prevent the cursor from moving in the input when using the up and down arrow keys
if (
event.code === 'ArrowUp' ||
event.code === 'ArrowDown'
) {
event.preventDefault();
}
}
switchOption(direction) {
if (!this.getAttribute('open')) return;
const moveUp = direction === 'up';
const selectedElement = this.querySelector('[aria-selected="true"]');
const allElements = this.querySelectorAll('li');
let activeElement = this.querySelector('li');
if (moveUp && !selectedElement) return;
this.statusElement.textContent = '';
if (!moveUp && selectedElement) {
activeElement = selectedElement.nextElementSibling || allElements[0];
} else if (moveUp) {
activeElement = selectedElement.previousElementSibling || allElements[allElements.length - 1];
}
if (activeElement === selectedElement) return;
activeElement.setAttribute('aria-selected', true);
if (selectedElement) selectedElement.setAttribute('aria-selected', false);
this.setLiveRegionText(activeElement.textContent);
this.input.setAttribute('aria-activedescendant', activeElement.id);
}
selectOption() {
const selectedProduct = this.querySelector('[aria-selected="true"] a, [aria-selected="true"] button');
if (selectedProduct) selectedProduct.click();
}
getSearchResults(searchTerm) {
const queryKey = searchTerm.replace(" ", "-").toLowerCase();
this.setLiveRegionLoadingState();
if (this.cachedResults[queryKey]) {
this.renderSearchResults(this.cachedResults[queryKey]);
return;
}
fetch(`${routes.predictive_search_url}?q=${encodeURIComponent(searchTerm)}&${encodeURIComponent('resources[type]')}=product&${encodeURIComponent('resources[limit]')}=4§ion_id=predictive-search`)
.then((response) => {
if (!response.ok) {
var error = new Error(response.status);
this.close();
throw error;
}
return response.text();
})
.then((text) => {
const resultsMarkup = new DOMParser().parseFromString(text, 'text/html').querySelector('#shopify-section-predictive-search').innerHTML;
this.cachedResults[queryKey] = resultsMarkup;
this.renderSearchResults(resultsMarkup);
})
.catch((error) => {
this.close();
throw error;
});
}
setLiveRegionLoadingState() {
this.statusElement = this.statusElement || this.querySelector('.predictive-search-status');
this.loadingText = this.loadingText || this.getAttribute('data-loading-text');
this.setLiveRegionText(this.loadingText);
this.setAttribute('loading', true);
}
setLiveRegionText(statusText) {
this.statusElement.setAttribute('aria-hidden', 'false');
this.statusElement.textContent = statusText;
setTimeout(() => {
this.statusElement.setAttribute('aria-hidden', 'true');
}, 1000);
}
renderSearchResults(resultsMarkup) {
this.predictiveSearchResults.innerHTML = resultsMarkup;
this.setAttribute('results', true);
this.setLiveRegionResults();
this.open();
}
setLiveRegionResults() {
this.removeAttribute('loading');
this.setLiveRegionText(this.querySelector('[data-predictive-search-live-region-count-value]').textContent);
}
getResultsMaxHeight() {
this.resultsMaxHeight = window.innerHeight - document.getElementById('shopify-section-header').getBoundingClientRect().bottom;
return this.resultsMaxHeight;
}
open() {
this.predictiveSearchResults.style.maxHeight = this.resultsMaxHeight || `${this.getResultsMaxHeight()}px`;
this.setAttribute('open', true);
this.input.setAttribute('aria-expanded', true);
}
close(clearSearchTerm = false) {
if (clearSearchTerm) {
this.input.value = '';
this.removeAttribute('results');
}
const selected = this.querySelector('[aria-selected="true"]');
if (selected) selected.setAttribute('aria-selected', false);
this.input.setAttribute('aria-activedescendant', '');
this.removeAttribute('open');
this.input.setAttribute('aria-expanded', false);
this.resultsMaxHeight = false
this.predictiveSearchResults.removeAttribute('style');
}
}
customElements.define('predictive-search', PredictiveSearch);
- Same create component-predictive-search.css file and paste this code,
.predictive-search {
display: none;
position: absolute;
top: calc(100% + 0.1rem);
width: calc(100% + 0.2rem);
left: -0.1rem;
border: 0.1rem solid rgba(var(--color-foreground), 0.2);
background-color: rgb(var(--color-background));
z-index: 3;
}
.predictive-search--search-template {
z-index: 2
}
@media screen and (max-width: 749px) {
.predictive-search--header {
right: 0;
left: 0;
top: 100%;
}
}
@media screen and (max-width: 989px) {
.predictive-search {
overflow-y: auto;
-webkit-overflow-scrolling: touch;
}
}
@media screen and (min-width: 750px) {
.predictive-search {
border-top: none;
}
.header predictive-search {
position: relative;
}
}
predictive-search[open] .predictive-search,
predictive-search[loading] .predictive-search {
display: block;
}
.predictive-search__heading {
border-bottom: 0.1rem solid rgba(var(--color-foreground), 0.08);
font-size: 1.2rem;
text-transform: uppercase;
margin: 0 auto;
padding: 1.5rem 0 0.75rem;
display: flex;
justify-content: space-between;
align-items: center;
width: calc(100% - 4rem);
color: rgba(var(--color-foreground), 0.7);
}
predictive-search .spinner {
width: 1.5rem;
height: 1.5rem;
line-height: 0;
}
.predictive-search__heading .spinner {
margin: 0 0.2rem 0 2rem;
}
predictive-search:not([loading]) .predictive-search__heading .spinner,
predictive-search:not([loading]) .predictive-search__loading-state,
predictive-search:not([loading]) .predictive-search-status__loading {
display: none;
}
predictive-search[loading] .predictive-search__loading-state {
display: flex;
justify-content: center;
padding: 1rem;
}
predictive-search[loading] .predictive-search__heading ~ .predictive-search__loading-state,
predictive-search[loading] .predictive-search__results-list:first-child {
display: none;
}
.predictive-search__list-item:nth-last-child(2) {
border-bottom: 0.1rem solid rgba(var(--color-foreground), 0.08);
}
.predictive-search__list-item[aria-selected="true"] > *,
.predictive-search__list-item:hover > * {
color: rgb(var(--color-foreground));
background-color: rgba(var(--color-foreground), 0.04);
}
.predictive-search__list-item[aria-selected="true"] .predictive-search__item-heading,
.predictive-search__list-item:hover .predictive-search__item-heading {
text-decoration: underline;
text-underline-offset: 0.3rem;
}
.predictive-search__item {
display: flex;
padding: 1rem 2rem;
text-align: left;
text-decoration: none;
width: 100%;
}
.predictive-search__item--link {
display: grid;
grid-template-columns: 5rem 1fr;
grid-column-gap: 2rem;
grid-template-areas: 'product-image product-content';
}
.predictive-search__item-content {
grid-area: product-content;
display: flex;
flex-direction: column;
}
.predictive-search__item-content--centered {
justify-content: center;
}
.predictive-search__item-vendor {
font-size: 0.9rem;
}
.predictive-search__item-heading {
margin: 0;
}
.predictive-search__item .price {
color: rgba(var(--color-foreground), 0.7);
font-size: 1.2rem;
}
.predictive-search__item-vendor + .predictive-search__item-heading,
.predictive-search .price {
margin-top: 0.5rem;
}
.predictive-search__item--term {
justify-content: space-between;
align-items: center;
padding: 1.3rem 2rem;
word-break: break-all;
line-height: 1.4;
}
@media screen and (min-width: 750px) {
.predictive-search__item--term {
padding-top: 1rem;
padding-bottom: 1rem;
}
}
.predictive-search__item--term .icon-arrow {
width: 1.4rem;
height: 1.4rem;
flex-shrink: 0;
margin-left: 2rem;
color: rgb(var(--color-link));
}
.predictive-search__image {
grid-area: product-image;
object-fit: contain;
font-family: 'object-fit: contain';
}
- Add this code in the theme.liquid.
{%- if settings.predictive_search_enabled -%}
{%- endif -%}
{%- if settings.predictive_search_enabled -%}
{%- endif -%}
render the predictive-search.liquid file in theme.liquid
I hope this points will work.
Thank you.