Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@emiliotapia
Last active November 20, 2020 00:14
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emiliotapia/65495d8580890c815a85da4f40dca1d4 to your computer and use it in GitHub Desktop.
Save emiliotapia/65495d8580890c815a85da4f40dca1d4 to your computer and use it in GitHub Desktop.
Recent collections for Shopify
{%- comment -%}
/sections/recent-collection-item.liquid
{%- endcomment -%}
<div class="recent-collections__collection">
<a href="{{collection.url}}">
<div class="recent-collections__collection-title">
{{collection.title}}
</div>
{%- assign img = collection.image -%}
{% unless img -%}
{%- assign img = collection.products[0].featured_image -%}
{%- endunless -%}
<img
src="{{ img | img_url: "400x400"}}"
alt="{{collection.title}}"
/>
</a>
</div>
{%- comment -%}
/snippets/recent-collections.liquid
{%- endcomment -%}
{%- unless quantity -%}
{%- assign quantity = 4 -%}
{%- endunless -%}
<div id="recent-collections" data-qty="{{quantity}}">
</div>
<script>
(async function(){
const lsRecentCollections = localStorage.getItem("recentCollections");
const recentCollectionsContainer = document.getElementById("recent-collections");
let currentCollection = "";
{%- if template.name == "collection" -%}
currentCollection = "{{collection.handle}}";
{%- endif -%}
if (lsRecentCollections && recentCollectionsContainer) {
let quantity = recentCollectionsContainer.getAttribute("data-qty");
const recentCollections = JSON.parse(lsRecentCollections).filter(c=>c!=currentCollection);
for (let i = 0; i < Math.min(quantity,recentCollections.length); i++ ) {
let response = await fetch("/collections/"+recentCollections[i]+"?section_id=recent-collection-item");
let responseData = await response.text();
var collectionDiv = document.createElement("div");
collectionDiv.innerHTML = responseData;
recentCollectionsContainer.append(collectionDiv.firstChild.firstChild);
}
}
})()
</script>
<script>
{%- if template.name == "collection" -%}
{%- unless max_quantity -%}
{%- assign max_quantity = 20 -%}
{%- endunless -%}
(function(){
let lsRecentCollections = localStorage.getItem("recentCollections");
let recentCollections = [];
if (lsRecentCollections) {
recentCollections = JSON.parse(lsRecentCollections);
}
const currentCollection = "{{collection.handle}}";
const collectionIndex = recentCollections.indexOf(currentCollection);
if(collectionIndex!=-1) {
recentCollections.splice(collectionIndex,1);
}
recentCollections.unshift(currentCollection);
recentCollections = recentCollections.slice(0,{{max_quantity}});
localStorage.setItem("recentCollections",JSON.stringify(recentCollections));
})();
{%- endif -%}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment