Skip to content

Instantly share code, notes, and snippets.

@denisoster
Created February 5, 2020 19:53
Show Gist options
  • Select an option

  • Save denisoster/fa4ea0a4b91147a33c1996a842801ed8 to your computer and use it in GitHub Desktop.

Select an option

Save denisoster/fa4ea0a4b91147a33c1996a842801ed8 to your computer and use it in GitHub Desktop.
Filter = {
url: '/catalogs/',
ajax: "/ajax_query",
parent: "body",
res_block: ".sort_result_cards",
is_need_change_sluider: false,
locale:window.location.pathname.replace(/^\/([^\/]*).*$/, '$1'),
Init: function Init() {
var data = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
this.ajax = data["ajax"] || this.ajax;
this.url = data["url"] || this.url;
this.parent = data["parent"] || this.parent;
this.res_block = data["res_block"] || this.res_block;
thet = this;
$(this.parent).on("change", "*[data-filter]", function (e) {
if ($(this).attr("data-filter")!="min" && $(this).attr("data-filter")!="max") {
thet.is_need_change_sluider=true;
}
if($(this).attr("data-filter")=="type"){
thet.Query(1,true);
}else{
thet.Query(1);
}
// console.log("change")
});
$(this.parent).on("click", ".pagination a",function() {
thet.Query(thet.parseURLParams($(this).attr("href"))["page"][0])
// console.log("page")
return false;
})
$(this.parent).on("click", "a[data-filter-link]", function () {
$('a[data-filter-link="'+$(this).attr("data-filter-link")+'"]').removeClass("active");
$(this).addClass("active")
thet.Query(1);
// console.log("change 1")
return false;
});
$(this.parent).on("click", ".sbros_filtr" ,function() {
thet.AjaxQuery({});
return false;
})
this.WriteSortLinks()
},
Collection: function Collection() {
var data_ajax = {};
$(this.parent + " *[data-filter]").each(function () {
var key = $(this).attr("data-filter");
var get = 0;
if ($(this).is("select")) {
get = $(this).find("option:selected").val();
} else {
if ($(this).attr("type") == "checkbox") {
if (get = $(this).prop("checked")) {
get = $(this).val();
} else {
return;
}
} else {
get = $(this).val();
}
}
if (data_ajax[key]) {
if (Array.isArray(data_ajax[key])) {
data_ajax[key].push(get);
} else {
data_ajax[key] = [data_ajax[key], get];
}
} else {
data_ajax[key] = get;
}
});
$(this.parent + " a.active[data-filter-link]").each(function() {
var key = $(this).attr("data-filter-link");
var get = $(this).attr("data-filter-link-get");
if (data_ajax[key]) {
if (Array.isArray(data_ajax[key])) {
data_ajax[key].push(get);
} else {
data_ajax[key] = [data_ajax[key], get];
}
} else {
data_ajax[key] = get;
}
})
return data_ajax;
},
CallbackSelect :function(some) {
return function() {
// console.log($(some))
// console.log($(some).find('option:selected'))
$(some).find('option:selected').removeAttr('selected');
// console.log($(some).find('option[value=""]'))
$(some).find('option[value=""]').attr('selected', "selected");
$(some).trigger("change")
}
},
CallbackClick :function(some) {
return function() {
$(some).click()
}
},
CollectionName: function CollectionName() {
var data_ajax = [];
thet=this
$(this.parent + ' *[data-filter]:not([data-filter="min"]):not([data-filter="max"]):not([data-filter="sort"])').each(function () {
var key = $(this).attr("data-filter");
var get = 0;
if ($(this).is("select")) {
some = $(this).find("option:selected")
if ($(some).val()!=""){
that_s=$(this)
get = [$(some).text() , thet.CallbackSelect(that_s)]
}
} else {
if ($(this).attr("type") == "checkbox") {
if ($(this).prop("checked")) {
some = $(this).parent().find("p");
that_s=$(this)
get = [$(some).contents().not($(some).children()).text() , thet.CallbackClick(that_s)];
}
} else {
return;
}
}
if (get){
data_ajax.push(get);
}
});
return data_ajax;
},
Query: function Query(page , type ) {
var data_ajax = this.Collection();
data_ajax["page"]=page||1
if (type){
data_ajax["brand"]=""
data_ajax["model"]=""
}
if(this.is_need_change_sluider){
delete data_ajax["min"];
delete data_ajax["max"];
}
this.AjaxQuery(data_ajax);
// TODO
// this.scroll();
},
AjaxQuery:function AjaxQuery(data_ajax) {
var thet = this;
$(this.res_block).append('<div class="filter-load" style="background: rgba(0,0,0,0.15);top:0;left:0;position:fixed;z-index:900;width:100%;height:100%;display: -webkit-flex; display: -moz-flex; display: -ms-flex; display: -o-flex; display: flex; -webkit-align-items: center; -moz-align-items: center; -ms-align-items: center; -o-align-items: center; align-items: center; -webkit-justify-content: center; -moz-justify-content: center; -ms-justify-content: center; -o-justify-content: center; justify-content: center;"><svg width="100px" height="100px" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" preserveAspectRatio="xMidYMid" class="uil-default"><rect x="0" y="0" width="100" height="100" fill="none" class="bk"></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(0 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.6s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(30 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.5499999999999999s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(60 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.5s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(90 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.44999999999999996s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(120 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.39999999999999997s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(150 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.35000000000000003s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(180 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.3s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(210 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.25s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(240 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.19999999999999998s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(270 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.15s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(300 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.09999999999999999s" repeatCount="indefinite"/></rect><rect x="46.5" y="40" width="7" height="20" rx="5" ry="5" fill="#eaa926" transform="rotate(330 50 50) translate(0 -30)"> <animate attributeName="opacity" from="1" to="0" dur="0.6s" begin="-0.049999999999999996s" repeatCount="indefinite"/></rect></svg></div>')
$.ajax({
url: "/"+this.locale+this.ajax,
data: data_ajax,
success: function success(data) {
// console.log(data);
thet.UpdateSelect("brand", data.brands, data_ajax);
thet.UpdateSelect("type", data.types, data_ajax);
thet.UpdateSelectOptgroup("model", data.model, data_ajax);
$(this.parent + " .chosen-select").trigger("chosen:updated");
thet.UpdateFilters("filter", data.filter, data_ajax);
thet.UpdateContainer(data,data_ajax);
thet.UpdateHistory(data_ajax);
thet.UpdateBredcrams();
$(this.parent + " .filter-load").remove()
}
});
},
UpdateBredcrams: function UpdateBredcrams () {
$(".bread_cr>span").slice(2).remove()
$(" select[data-filter] option[selected='selected']").each(function() {
if ($(this).attr("data-slug")){
$(".bread_cr").append('<span itemscope="" itemprop="itemListElement" itemtype="http://schema.org/ListItem">\
<a href="'+$(".bread_cr>span:last > a").attr("href")+'/'+$(this).parent().attr("data-filter")+'-'+$(this).attr("data-slug")+'" title="Жатка" itemprop="item">\
<span itemprop="name">'+$(this).text()+'</span>\
</a>\
</span>')
}
})
$(" select[data-filter] option[selected='selected']")
var res = $(".minimenu a.active").text()
if(res == "Все"){ res="Справочник"}
if ($(" select[data-filter] option[selected='selected'][value!='']").length>0){
res+=": "
$(" select[data-filter] option[selected='selected'][value!='']").each(function() {
res+=$(this).text()+" "
})
}
$(".katalogspravoch h1").text(res)
},
UpdateHistory: function UpdateHistory(data_ajax) {
helper_bool=false
helper=''
// console.log("UpdateHistory")
if (data_ajax["type"]) {
if (helper_bool) {
helper+="/"
}
helper+="type-"+$(this.parent + ' *[data-filter="type"] option:selected').attr('data-slug');
helper_bool=true
delete data_ajax["type"]
};
// console.log('data_ajax["type"]='+data_ajax["type"])
if (data_ajax["brand"]) {
if (helper_bool) {
helper+="/"
}
helper+="brand-"+$(this.parent + ' *[data-filter="brand"] option:selected').attr('data-slug');
helper_bool=true
delete data_ajax["brand"]
};
// console.log('data_ajax["brand"]='+data_ajax["brand"])
if (data_ajax["model"]) {
if (helper_bool) {
helper+="/"
}
helper+="model-"+$(this.parent + ' *[data-filter="model"] option:selected').attr('data-slug');
helper_bool=true
delete data_ajax["model"]
};
// console.log('data_ajax["model"]='+data_ajax["model"])
new_data_ajax={}
get=''
for (d in data_ajax){
if (data_ajax[d] && data_ajax[d]!="" && d!="type" && d!="brand" && d!="model") {
new_data_ajax[d]=data_ajax[d]
}
}
if (Object.keys(new_data_ajax).length>0) {
get="?"+$.param(new_data_ajax)
}
$(".locale_ua").attr("href" , "/ua"+this.url+helper+get)
$(".locale_ru").attr("href" , "/ru"+this.url+helper+get)
history.pushState(data_ajax, "", "/"+this.locale+this.url+helper+get);
},
UpdateSelect: function UpdateSelect(name, data, data_ajax) {
var select=$(this.parent + ' .chosen-select[data-filter="' + name+'"]')
$(select).html("");
helper = true;
if ( data.length == 1 ){ data_ajax[name] = data[0][0] }
for (object in data) {
if (data_ajax[name] == data[object][0] ) {
helper = false;
$(select).append('<option data-slug="'+data[object][2]+'" value="' + data[object][0] + '" selected="selected">' + data[object][1] + '</option>');
} else {
$(select).append('<option data-slug="'+data[object][2]+'" value="' + data[object][0] + '">' + data[object][1] + '</option>');
}
}
if (helper) {
$(select).prepend('<option value="" selected="selected">Выберите</option>');
} else {
$(select).append('<option value="">Сбросить</option>');
}
$(select).trigger("chosen:updated")
},
UpdateSelectOptgroup: function UpdateSelectOptgroup(name, data, data_ajax) {
var select=$(this.parent + ' .chosen-select[data-filter="' + name+'"]')
$(select).html("");
helper = true;
for (object in data) {
s = '';
for (some in data[object]) {
if (data_ajax[name] == data[object][some][0]) {
helper = false;
s += '<option data-slug="'+data[object][some][2]+'" value="' + data[object][some][0] + '" selected="selected">' + data[object][some][1] + '</option>';
} else {
s += '<option data-slug="'+data[object][some][2]+'" value="' + data[object][some][0] + '">' + data[object][some][1] + '</option>';
}
}
$(select).append('<optgroup label=' + object + '>' + s + '</optgroup>');
}
if (helper) {
$(select).prepend('<option value="" selected="selected">Выберите</option>');
} else {
$(select).append('<option value="">Сбросить</option>');
}
$(select).trigger("chosen:updated")
},
UpdateFilters: function UpdateFilters(name, data, data_ajax) {
$(".filter-toggle").remove();
s = '';
arr=data_ajax["filter"]
Array.isArray(arr)?arr:arr=[arr];
for (filter_groop in data) {
s += '<div class="filtr_block filter-toggle">\
<div class="filtr_uzel">\
<h3>' + data[filter_groop][0] + '</h3>';
for (filter in data[filter_groop][1]) {
if (arr.includes(""+data[filter_groop][1][filter].val)) {
s += '\
<label for="filterrific_with_any_filter_ids' + data[filter_groop][1][filter].val + '" class="technica_label">\
<input id="filterrific_with_any_filter_ids' + data[filter_groop][1][filter].val + '" data-filter="filter" type="checkbox" value="' + data[filter_groop][1][filter].val + '" name="filterrific[with_any_filter_ids]" checked>\
<p class="technica_text">' + data[filter_groop][1][filter].name + ' <span>(' + data[filter_groop][1][filter].count + ')</span></p>\
</label>\
';
} else {
s += '\
<label for="filterrific_with_any_filter_ids' + data[filter_groop][1][filter].val + '" class="technica_label">\
<input id="filterrific_with_any_filter_ids' + data[filter_groop][1][filter].val + '" data-filter="filter" type="checkbox" value="' + data[filter_groop][1][filter].val + '" name="filterrific[with_any_filter_ids]">\
<p class="technica_text">' + data[filter_groop][1][filter].name + ' <span>(' + data[filter_groop][1][filter].count + ')</span></p>\
</label>\
';
}
}
s += "</div></div>";
}
$(".filtr_variation").after(s);
},
UpdateContainer: function UpdateContainer(data , data_ajax) {
this.ClearContainer()
this.WriteGoods(data.goods);
this.WriteSchemasAndArticle(data.articles);
this.WritePages((data.goods||data.schemes||[]).length , data.count , +data_ajax["page"]||1)
this.WriteSortLinks()
this.WriteSeo(data.seo_title, data.seo_text)
if ( this.is_need_change_sluider && document.getElementById('html5')!=null) {
this.is_need_change_sluider=false
var html5Slider = document.getElementById('html5');
html5Slider.noUiSlider.off('set', function(){});
html5Slider.noUiSlider.updateOptions({
range: {
'min': data["min_price"]||0,
'max': data["max_price"]||100
}
});
html5Slider.noUiSlider.set([data["min_price"],data["max_price"]])
html5Slider.noUiSlider.on('set', function(){
helper_timer = 0
helper_timer=setTimeout(function() { $("#input-number").trigger("change")}, 300)
});
}
},
ClearContainer: function ClearContainer() {
$(this.res_block).html("");
},
WriteSeo: function WriteSeo(title , text) {
$(".seo .block").html(text)
$("title").text(title)
},
WriteGoods: function WriteGoods(goods) {
for (good in goods) {
$(this.res_block).append('<div class="card cart_object">\
<div class="card_info">\
<a href="' + goods[good].src + '">\
<div class="card_info_title" data-cart="title">' + goods[good].title + '</div>\
</a>\
<div class="card_info_code">\
<p class="product_code" data-cart="number">' + goods[good].number + '</p>\
<p class="product_number" data-cart="id">' + goods[good].id + '</p>\
</div>\
</div>\
<a href="' + goods[good].src + '">\
<div class="card_img">\
<img data-cart-img="img" src="' + goods[good].img + '" alt="' + goods[good].title + '">\
</div>\
</a> \
<p class="card_status">' + goods[good].status + '</p>\
<div class="card_purchase">\
<p class="card_price" data-cart="price">' + goods[good].price + '</p>\
<button type="button" class="card_buy cart_add">'+(this.locale=="ru"?"Купить":"Купити")+'</button>\
</div>\
<p class="card_brands">' + goods[good].brand + '</p>\
</div>');
}
},
WriteSchemasAndArticle: function WriteSchemasAndArticle(scope) {
// console.log("scope")
// console.log(scope)
for (object in scope) {
if (scope[object].article) {
helper='<p class="spravoch_selected_object spravoch_selected-article">Статья</p>'
}else{
helper='<p class="spravoch_selected_object spravoch_selected-shem">Схема</p>'
}
$(this.res_block).prepend('<div class="spravoch_selected_item"><div class="spravoch_selected_item_top"><p class="spravoch_selected_topic">'+scope[object].type+'</p>'+helper+'</div> <div class="spravoch_selected_item_main"><a href="'+"/"+this.locale+scope[object].src+'" class="spravoch_selected-title">'+scope[object].title+'</a><a href="'+"/"+this.locale+scope[object].src+'"><div class="spravoch_selected_image"><img class="spravoch_selected_img" src="'+scope[object].img+'" alt=""> </div> </a> <div class="spravoch_selected-text_wrap"> <p class="spravoch_selected-text">'+scope[object].about+'</p> </div> <a href="'+scope[object].src+'" class="spravoch_selected-link">Читать далее...</a> </div> </div>')
}
},
WritePages: function WritePages(objects_on_page, objects_all , page){
$(".navigation_number_goods").text(objects_all)
// console.log("objects_on_page "+objects_on_page)
// console.log("objects_all "+objects_all)
// console.log("page "+page)
//2 ... 4 {page} 4 ... 2
page_all=Math.ceil(objects_all/24)
if (page_all>1) {
helper='';
h=true
for (var u = 1; u <=page_all; u++) {
hh=h
if (3>u||u>page_all-2||( u<=(page+4) && u>=(page-4) )) {
h=true
u==page?helper+='<span class="current">'+u+'</span> ':helper+='<a href="/catalogs/type-press-podborschik?page='+u+'">'+u+'</a> '
}else{
h=false
}
if (hh!=h && h!=true) {
helper+='<span class="gap">…</span> '
}
}
if (page>=page_all) {
helper+='<span class="next_page disabled">\
<a class="next_page" rel="next">\
<i class="fa fa-chevron-right" aria-hidden="true"></i>\
</a>\
</span> '
}else{
helper+='<a class="next_page" rel="next" href="/catalogs/type-press-podborschik?page='+(+page+1)+'">\
<i class="fa fa-chevron-right" aria-hidden="true"></i>\
</a> '
}
if (page<2) {
helper='<span class="previous_page disabled">\
<a class="previous_page" rel="previous">\
<i class="fa fa-chevron-left" aria-hidden="true"></i>\
</a>\
</span> '+helper
}else{
helper='<a class="previous_page" rel="previous" href="/catalogs/type-press-podborschik?page='+(+page-1)+'">\
<i class="fa fa-chevron-left" aria-hidden="true"></i>\
</a> '+helper
}
$(this.res_block).append('<div class="sort_pages">\
<div class="shown_products">\
<p>Показано <span class="shown_period_quan">'+ ((page-1)*24+1) +'-'+ ((page-1)*24+objects_on_page)+'</span> с <span class="shown_max_quan">'+objects_all+'</span> '+(this.locale=="ru"?"товаров":"товарів")+'</p>\
</div>\
<div class="shown_products_pagination">\
<div class="products_paginate">\
<div class="pagination">'+helper+'</div>\
</div>\
</div>\
</div>')
}
},
WriteSortLinks :function WriteSortLinks() {
$( this.parent+" .navigation_sort_links").html("");
sort_links=this.CollectionName()
$( this.parent+" .navigation_sort_links" ).off( ".validator" );
for(i in sort_links){
$(".navigation_sort_links").append('<li id=navigation_sort_link'+i+' ><a class="navigation_sort_link">'+sort_links[i][0]+'\
<div><span></span><span></span></div>\
</a></li>')
$(this.parent+" .navigation_sort_links").on("click.validator" , "#navigation_sort_link"+i , sort_links[i][1])
}
},
parseURLParams :function parseURLParams(url) {
var queryStart = url.indexOf("?") + 1,
queryEnd = url.indexOf("#") + 1 || url.length + 1,
query = url.slice(queryStart, queryEnd - 1),
pairs = query.replace(/\+/g, " ").split("&"),
parms = {}, i, n, v, nv;
if (query === url || query === "") return;
for (i = 0; i < pairs.length; i++) {
nv = pairs[i].split("=", 2);
n = decodeURIComponent(nv[0]);
v = decodeURIComponent(nv[1]);
if (!parms.hasOwnProperty(n)) parms[n] = [];
parms[n].push(nv.length === 2 ? v : null);
}
return parms;
}
,
scroll:function scrol() {
console.log('this.hash');
console.log(this);
var target = $(".main_catalog .block");
target = target.length ? target : $('[name=' + this.hash.slice(1) + ']');
// Does a scroll target exist?
if (target.length) {
// Only prevent default if animation is actually gonna happen
$('html, body').animate({
scrollTop: target.offset().top
}, 300);
}
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment