Skip to content

Instantly share code, notes, and snippets.

@dviedma
Created August 28, 2020 15:46
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 dviedma/71c883a71b976baa083103aa8be3918a to your computer and use it in GitHub Desktop.
Save dviedma/71c883a71b976baa083103aa8be3918a to your computer and use it in GitHub Desktop.
<script>
var $jquery = window.jQuery,
isResultsLoaded = {},
select = (query, item = document) => item.querySelector(query),
selectAll = (query, item = document) => item.querySelectorAll(query),
insertAfter = (newNode, referenceNode) => referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling),
productLineEl,
productLine2,
filterDropdownEls,
filtersEls,
filterMobileEls,
searchResultsContainerEl,
filterRegexp = /filter (.*?): /gmi,
isOrderBinded = false,
searchParameter;
////////////// clp-swatches.js startt
function setRolloverImages(containerEl, image1Str, image2Str) {
// remove product images except the placeholder
[...containerEl.children].forEach( elem => {
if(elem.classList.contains("isp_product_image")){
elem.parentNode.removeChild(elem)
}
})
containerEl.innerHTML +=
"<img class='isp_product_image isp_product_image--top' src='" + image1Str + "'>" +
"<img class='isp_product_image isp_product_image--bottom' src='" + image2Str + "'>"
containerEl.addEventListener("mouseover", (e) => {
select(".isp_product_image--top", containerEl).style.zIndex = 2;
});
containerEl.addEventListener("mouseout", (e) => {
select(".isp_product_image--top", containerEl).style.zIndex = 10;
});
}
function removeDuplicateUsingSet(arr){
let unique_array = Array.from(new Set(arr))
return unique_array
}
function chunkSearch() {
//Removing duplicated values AND passing it to chunk variable
var uniqueSearchParameter = removeDuplicateUsingSet(searchParameter), chunk;
// Chunking the search
while (uniqueSearchParameter.length > 0) {
//Separing into 3 SKU at the time to avoid issue on very large pages like All Swims
chunk = uniqueSearchParameter.splice(0,3);
//Converting into a String
var parameterToString = chunk.toString();
//Replacing commas with " OR " to the Shopify url search
var parameterToStringURL = parameterToString.replace(/,/g, ' OR ');
//Building the search's variable
var searchURLclp = '/search?type=product&q=' + parameterToStringURL;
//Calling getOthersCLP function with search parameter
getOthersCLP(searchURLclp, function(searchResultsObject) {
// Loop over all the products on the page and add their swatches
LoopOnProducts('{{this_sku[1]}}', searchResultsObject);
//Showing Swatches by hovering options
ShowingSwatches();
});
}
}
function getOthersCLP(searchURLclp, callback){
var searchResultsObject = {};
jQuery.getJSON(searchURLclp + '&view=va', function(data){
if(data.results_count > 0){
var searchJson = data;
var searchResults = searchJson.results || [];
// Add each product in search results to searchResultsObject keyed by SKU style
searchResults.forEach(function(result) {
//Storing the first "term" of the sku value. Example: "918T"
if(result.sku != null) {
var skuStyle = result.sku.split('-')[0];
if (searchResultsObject[skuStyle]) {
searchResultsObject[skuStyle].push(result);
} else {
searchResultsObject[skuStyle] = [result];
}
}
});
callback(searchResultsObject);
}//end if
});
return;
};
//Loop on Produtos
function LoopOnProducts(thisColor, searchResultsObject){
// Get all the products
var productsOnPage = jQuery('.isp_product_info');
// Storing the SKU on each product in a data-attribute on the HTML (.collection-product)
productsOnPage.each(function() {
var productSwatchesDiv = jQuery(this);
// Declaring var numberOfSwatches again to fix the console issue
var sku = productSwatchesDiv.find(".isp_product_sku")[0].innerText.split(" ")[1].split("-")[0]
//SKU of the data attribute
var skuStyle = sku;
var otherProductSwatches = searchResultsObject[skuStyle];
if (otherProductSwatches) {
//Getting the number of Swatches available
var numberOfSwatches = otherProductSwatches.length;
SwatchesTotalCounter(productSwatchesDiv, numberOfSwatches)
// Swatches Counter
if(numberOfSwatches > 8) {
numberOfSwatches = numberOfSwatches - 8;
SwatchesCounter(productSwatchesDiv, numberOfSwatches);
}
// Modifing the product's HTML to show available swatches from otherProductSwatches
SwatchesDOM(otherProductSwatches, thisColor, productSwatchesDiv);
}
// Defaulting the color name to the first one (DV: no need)
var defaultColorName = productSwatchesDiv.data('product-color'); //Getting the data attribute of the color name
productSwatchesDiv.find('.va_color_name').text(defaultColorName);
//Showing Swatches options on preview image hover
ShowingHiddingSwatches(productSwatchesDiv, defaultColorName);
});
}
// Swatches Counter
function SwatchesCounter(productSwatchesDiv, numberOfSwatches){
//Building the html to show the Swatch counter number with condition in case it's up to 20
var htmlCounter = "+" + numberOfSwatches +" more";
var existingCounter = productSwatchesDiv.find('.va_counter_swatches_value');
if (existingCounter.length) {
if (existingCounter.text() === htmlCounter) {
return;
}
existingCounter.text(htmlCounter);
return;
}
var html = `
<span class="va_counter_swatches_value">${htmlCounter}</span>
`;
var productSwatchCounterDiv = productSwatchesDiv.find('.isp_product_image_href');
productSwatchCounterDiv.append(html);
};
function SwatchesTotalCounter(productSwatchesDiv, numberOfSwatches){
var label = numberOfSwatches > 1 ? numberOfSwatches + " Colors Available" : numberOfSwatches + " Color Available"
var html = `
<p class="label-colors">${label}</p>
`;
var productSwatchCounterDiv = productSwatchesDiv.find('.product-card__variants-title');
productSwatchCounterDiv.append(html);
}
function SwatchesDOM(otherProductSwatches, thisColor, productSwatchesDiv){
var allSwatchesHtml = '';
// Modifing the product's HTML to show available swatches from otherProductSwatches
//Showing up only 8 swatches / Product
otherProductSwatches.slice(-8).forEach(function(result) {
var link = result.url;
var title = result.title;
var color = result.sku.split('-')[1];
var color_name = jQuery.trim(title.split('-')[1]);
var imageTop = result.imageTop;
var imageBottom = result.imageBottom;
var active = color == thisColor ? 'active' : ''; //This is not been used but I maybe would be helpful in case of active state been necessary
var cc_swatch = false;
var stripe_print = false;
var html = `
<span data-image-top="${imageTop}"
data-image-bottom="${imageBottom}"
title="${color_name}"
class="cc_swatch ${active}">
<div style="background-image: url(${result.swatch})"></div>
</span>`;
allSwatchesHtml += html;
});
//productSwatchesDiv.find('.va_color_list_clp').html(allSwatchesHtml);
var productSwatchCounterDiv = productSwatchesDiv.find('.isp_product_image_href');
productSwatchCounterDiv.append("<div class='swatches'>" + allSwatchesHtml+"</div>");
};
//Showing Swatches boubles options on preview image hover
function ShowingHiddingSwatches(productSwatchesDiv, defaultColorName) {
jQuery('.product-grid-item').bind({
mouseenter: function(){
if(!jQuery(this).find('.va_color_list_clp').hasClass('is-active')){
jQuery(this).find('.va_color_list_clp').addClass('is-active');
jQuery(this).find('.va_counter_swatches').addClass('hidden');
}
},
mouseleave: function(){
jQuery(this).find('.va_color_list_clp').removeClass('is-active');
jQuery(this).find('.va_counter_swatches').removeClass('hidden');
// Defaulting the color name to the stored one
productSwatchesDiv.find('.va_color_name').text(defaultColorName);
}
});
};
//Showing Swatches by hovering options
function ShowingSwatches() {
let liEl,
parentEl;
selectAll(".swatches span").forEach(function (elem, index) {
elem.addEventListener("click", (e)=> {
e.preventDefault();
liEl = e.target.closest('li');
parentEl = e.target.parentElement;
select('.product-card__variants-title', liEl).innerText = parentEl.getAttribute("title");
setRolloverImages(
select('.isp_product_image_href', liEl),
parentEl.getAttribute("data-image-top"),
parentEl.getAttribute("data-image-bottom")
)
})
});
};
////////////// clp-swatches.js end
function isInTags(productID, tagName) {
if(!ISP_PRODUCTS[productID].att) return false;
const tags = ISP_PRODUCTS[productID].att.find(attributes => attributes[0] === TAG_FILTER_NAME);
return tags && tags[1].find(tag => tag.toLowerCase() === tagName.toLowerCase())
}
const TAG_FILTER_NAME = "Tag";
const FEATURED_TAG_NAME = "collection-featured-product";
var __isp_new_jquery = 1;
$( document ).ready(function() {
// if (no filters applied && parent colleciton) 19 : 20;
__isp_options.products_per_page = (window.location.href.indexOf("narrow") < 0 && !select(".collection-child"))? 19 : 20;
});
var __isp_options = {
isp_serp_with_product_attributes: 1,
isp_serp_callback: function() {
/**
* 2 tile product for collection
*/
if (window.location.href.indexOf("/collections") > -1) {
$(".isp_grid_product").each(function () {
const productID = $(this).attr("product_id");
if (!this.classList.contains(FEATURED_TAG_NAME) && isInTags(productID, FEATURED_TAG_NAME)) {
this.classList.add(FEATURED_TAG_NAME);
}
});
}
if(window.location.href.indexOf("narrow") == -1) {
$("#isp_search_results_container").addClass("isp_search_results_container__not-filtered");
}else {
$("#isp_search_results_container").removeClass("isp_search_results_container__not-filtered");
}
/**
*
* FILTERS CUSTOMIZATIONS
*
*/
if(select("[facet_name='Color']") && select("[facet_name='Color']").getAttribute("loaded") != "true") {
filterEls = selectAll(".isp_facet_value_name span");
filterMobileEls = selectAll(".isp_single_mobile_facet span");
searchResultsContainerEl = select("#isp_search_results_container");
select("[facet_name='Color']").setAttribute("loaded", "true");
// Remove Filter ***: from the filter names in Desktop
if(filterEls) {
filterEls.forEach(function (elem, index) {
elem.innerText = elem.innerText.replace(filterRegexp, "");
})
}
// Remove Filter ***: from the filter names in Mobile
if(filterMobileEls) {
filterMobileEls.forEach(function (elem, index) {
elem.innerText = elem.innerText.replace(filterRegexp, "");
})
}
filterDropdownEls = selectAll(".isp_facet_title");
if(filterDropdownEls) {
filterDropdownEls.forEach(function (elem1, index) {
// Filters open and close (open and close ♫)
elem1.addEventListener("click", () => {
filterDropdownEls.forEach(function (elem2, index) {
if(elem1.getAttribute("title") != elem2.getAttribute("title")) {
elem2.classList.remove("filter-open");
}
});
elem1.classList.toggle("filter-open");
searchResultsContainerEl.style.marginTop = (elem1.nextElementSibling.clientHeight + 30) + "px";
});
// ReOrder Filters (from ISP documentation)
var order = ["Style" ,"Color" ,"Fabric" ,"Size"];
var el;
for (var i = order.length - 1; i > -1; i--) {
$(".isp_facet_title_name").each(function(index) {
$el = $(this);
if (order[i].split(" ")[0] == $el.text().split(" ")[0]) {
$(".isp_single_facet_wrapper").eq(index).prependTo( $(".isp_search_res_facets_container"));
}
})
}
// Add Filter count
let regExp = new RegExp(select("span",elem1).innerText.replace(" ", "%20"), "gm");
if((window.location.href.match(regExp) || []).length) {
select("span",elem1).innerText = select("span",elem1).innerText +
" (" +
(window.location.href.match(regExp) || []).length +
")";
}
})
}
// Order by open and close (open and close ♫)
if(!isOrderBinded) {
select("#isp_sorting_drop_container a").addEventListener("click", () => {
if(searchResultsContainerEl.classList.contains("orderby-opened")) {
searchResultsContainerEl.classList.remove("orderby-opened");
searchResultsContainerEl.style.marginTop = 0;
}else {
searchResultsContainerEl.classList.add("orderby-opened");
}
filterDropdownEls.forEach(function (elem2, index) {
elem2.classList.remove("filter-open");
});
});
isOrderBinded = true;
}
// Add "Clear All"
let filtersContainerEl = select(".isp_search_res_facets_container");
if(window.location.href.indexOf("narrow") > 0 && filtersContainerEl) {
filtersContainerEl.insertAdjacentHTML('beforeend', "<a href='" + window.location.origin + window.location.pathname + "' class='clear-all'>Clear All</a>");
if(select('.collection.child-collection')) {
select('.collection.child-collection').classList.add('filtered');
}
}else if(select(".clear-all")) {
select(".clear-all").remove();
}else if(select('.collection.child-collection')) {
select('.collection.child-collection').classList.remove('filtered');
}
// weird bug, make sure labels are there
// desktop
$(".isp_facet_title_name").each(function(index) {
$el = $(this);
//$el[0].innerText = $el.parent()[0].getAttribute("title");
})
window.scrollTo(0,0);
}
/**
*
* PRODUC GRID CUSTOMIZATIONS
*
*/
if(!select("#isp_center_container .product-card__variants-title")){
console.log("GRID");
let imageWrapperEl,
imageEl,
productId,
productInfoEl;
selectAll(".isp_grid_product").forEach(function (elem, index) {
productId = elem.getAttribute("product_id");
// Add product type on a second line
productLineEl = select(".isp_product_title", elem);
productLine2 = productLineEl.innerText.split(" - ")[1];
productLineEl.innerText = productLineEl.innerText.split(" - ")[0];
productLineEl.parentElement.innerHTML = productLineEl.parentElement.innerHTML +
"<br/>" +
"<p class='product-card__variants-title p3-type'>" + productLine2 + "</p>";
// Add Image rollover
imageWrapperEl = select(".isp_product_image_wrapper", elem);
imageWrapperEl.addEventListener("mouseover", (e) => {
if(e.target.getAttribute("isp_product_id") && ISP_PRODUCTS[e.target.getAttribute("isp_product_id")].rolloverImages) {
setRolloverImages(e.target.parentElement,
ISP_PRODUCTS[e.target.getAttribute("isp_product_id")].rolloverImages[0],
ISP_PRODUCTS[e.target.getAttribute("isp_product_id")].rolloverImages[1]);
}
});
// Add image placeholder
imageWrapperEl.querySelector("a").innerHTML += "<img class='isp_product_image--placeholder' src='https://cdn.shopify.com/s/files/1/0380/8467/3668/files/white.jpg?v=1596487707'>"
// Show/Hide Swatches
productInfoEl = select(".isp_grid_product", elem);
elem.addEventListener("mouseover", (e) => {
if(!!select(".swatches", elem))
select(".swatches", elem).style.display = "grid";
if(!!select(".va_counter_swatches_value", elem))
select(".va_counter_swatches_value", elem).style.display = "flex";
if(!!select(".label-colors", elem))
select(".label-colors", elem).style.display = "none";
});
elem.addEventListener("mouseout", (e) => {
if(!!select(".swatches", elem))
select(".swatches", elem).style.display = "none";
if(!!select(".va_counter_swatches_value", elem))
select(".va_counter_swatches_value", elem).style.display = "none";
if(!!select(".label-colors", elem))
select(".label-colors", elem).style.display = "flex";
});
// Build searchParameter for swatches
if (!searchParameter) {
searchParameter = [];
}
searchParameter.push(ISP_PRODUCTS[productId].sku.split("-")[0]);
const hasBrand = String(window.ISP_PRODUCTS[productId].att[1][1]).toLowerCase() || '';
if(hasBrand === 'brand card'){
let elem = select(`[product_id="${productId}"] .product-card__variants-title`).innerText;
select(`[product_id="${productId}"]`).classList.add('brand-card');
select(`[product_id="${productId}"] .isp_product_image_wrapper`).insertAdjacentHTML('beforeend', `<p class="product-card__variants-title p3-type">${elem}</p>`);
}
});
chunkSearch();
// mobile
let interval = setInterval(function(){
if(document.querySelector(".isp_mobile_filter")) {
clearInterval(interval);
// add labels
$(".isp_mobile_filter").each(function(index) {
$el = $(this);
$el[0].innerText = $el.parent()[0].getAttribute("facet_value").replace(filterRegexp, "");
})
$(".isp_mobile_swatch_title").each(function(index) {
$el = $(this);
$el[0].innerText = $el.parent()[0].getAttribute("facet_value").replace(filterRegexp, "");
})
}
}, 1000);
}
},
isp_serp_pre_filter_callback: function(event) {
window.scrollTo(0,0);
},
isp_dropdown_select_callback: function () {
console.log("open sesame 2");
}
}
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment