/
lr-ru_gitVerse
/
front
Обзор
Документация
Войти
/
lr-ru_gitVerse
/
front
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
build/js/script.js
21 110 строк
1 MB
Artem Naumov
init
28 окт 2024, 01:39
28 окт 2024, 01:39
9aa6803
Код
Авторство
О чём код?
!function(){"use strict";function o(){var o=window,t=document;if(!("scrollBehavior"in t.documentElement.style&&!0!==o.__forceSmoothScrollPolyfill__)){var l,e=o.HTMLElement||o.Element,r=468,i={scroll:o.scroll||o.scrollTo,scrollBy:o.scrollBy,elementScroll:e.prototype.scroll||n,scrollIntoView:e.prototype.scrollIntoView},s=o.performance&&o.performance.now?o.performance.now.bind(o.performance):Date.now,c=(l=o.navigator.userAgent,new RegExp(["MSIE ","Trident/","Edge/"].join("|")).test(l)?1:0);o.scroll=o.scrollTo=function(){void 0!==arguments[0]&&(!0!==f(arguments[0])?h.call(o,t.body,void 0!==arguments[0].left?~~arguments[0].left:o.scrollX||o.pageXOffset,void 0!==arguments[0].top?~~arguments[0].top:o.scrollY||o.pageYOffset):i.scroll.call(o,void 0!==arguments[0].left?arguments[0].left:"object"!=typeof arguments[0]?arguments[0]:o.scrollX||o.pageXOffset,void 0!==arguments[0].top?arguments[0].top:void 0!==arguments[1]?arguments[1]:o.scrollY||o.pageYOffset))},o.scrollBy=function(){void 0!==arguments[0]&&(f(arguments[0])?i.scrollBy.call(o,void 0!==arguments[0].left?arguments[0].left:"object"!=typeof arguments[0]?arguments[0]:0,void 0!==arguments[0].top?arguments[0].top:void 0!==arguments[1]?arguments[1]:0):h.call(o,t.body,~~arguments[0].left+(o.scrollX||o.pageXOffset),~~arguments[0].top+(o.scrollY||o.pageYOffset)))},e.prototype.scroll=e.prototype.scrollTo=function(){if(void 0!==arguments[0])if(!0!==f(arguments[0])){var o=arguments[0].left,t=arguments[0].top;h.call(this,this,void 0===o?this.scrollLeft:~~o,void 0===t?this.scrollTop:~~t)}else{if("number"==typeof arguments[0]&&void 0===arguments[1])throw new SyntaxError("Value could not be converted");i.elementScroll.call(this,void 0!==arguments[0].left?~~arguments[0].left:"object"!=typeof arguments[0]?~~arguments[0]:this.scrollLeft,void 0!==arguments[0].top?~~arguments[0].top:void 0!==arguments[1]?~~arguments[1]:this.scrollTop)}},e.prototype.scrollBy=function(){void 0!==arguments[0]&&(!0!==f(arguments[0])?this.scroll({left:~~arguments[0].left+this.scrollLeft,top:~~arguments[0].top+this.scrollTop,behavior:arguments[0].behavior}):i.elementScroll.call(this,void 0!==arguments[0].left?~~arguments[0].left+this.scrollLeft:~~arguments[0]+this.scrollLeft,void 0!==arguments[0].top?~~arguments[0].top+this.scrollTop:~~arguments[1]+this.scrollTop))},e.prototype.scrollIntoView=function(){if(!0!==f(arguments[0])){var l=function(o){for(;o!==t.body&&!1===(e=p(l=o,"Y")&&a(l,"Y"),r=p(l,"X")&&a(l,"X"),e||r);)o=o.parentNode||o.host;var l,e,r;return o}(this),e=l.getBoundingClientRect(),r=this.getBoundingClientRect();l!==t.body?(h.call(this,l,l.scrollLeft+r.left-e.left,l.scrollTop+r.top-e.top),"fixed"!==o.getComputedStyle(l).position&&o.scrollBy({left:e.left,top:e.top,behavior:"smooth"})):o.scrollBy({left:r.left,top:r.top,behavior:"smooth"})}else i.scrollIntoView.call(this,void 0===arguments[0]||arguments[0])}}function n(o,t){this.scrollLeft=o,this.scrollTop=t}function f(o){if(null===o||"object"!=typeof o||void 0===o.behavior||"auto"===o.behavior||"instant"===o.behavior)return!0;if("object"==typeof o&&"smooth"===o.behavior)return!1;throw new TypeError("behavior member of ScrollOptions "+o.behavior+" is not a valid value for enumeration ScrollBehavior.")}function p(o,t){return"Y"===t?o.clientHeight+c<o.scrollHeight:"X"===t?o.clientWidth+c<o.scrollWidth:void 0}function a(t,l){var e=o.getComputedStyle(t,null)["overflow"+l];return"auto"===e||"scroll"===e}function d(t){var l,e,i,c,n=(s()-t.startTime)/r;c=n=n>1?1:n,l=.5*(1-Math.cos(Math.PI*c)),e=t.startX+(t.x-t.startX)*l,i=t.startY+(t.y-t.startY)*l,t.method.call(t.scrollable,e,i),e===t.x&&i===t.y||o.requestAnimationFrame(d.bind(o,t))}function h(l,e,r){var c,f,p,a,h=s();l===t.body?(c=o,f=o.scrollX||o.pageXOffset,p=o.scrollY||o.pageYOffset,a=i.scroll):(c=l,f=l.scrollLeft,p=l.scrollTop,a=n),d({scrollable:c,method:a,startTime:h,startX:f,startY:p,x:e,y:r})}}"object"==typeof exports&&"undefined"!=typeof module?module.exports={polyfill:o}:o()}(); function newsPostAskModal() { let askButton = document.querySelectorAll('.bar-btns__ask'); let modalAsk = document.querySelector('.modal-ask'); let modalAskClose = document.querySelector('.modal-ask__form-close'); if (askButton === null || modalAsk === null || modalAskClose === null) { // console.log("askButton left html"); } else { for(let i = 0; i < askButton.length; i++){ askButton[i].addEventListener("click", function(e) { e.preventDefault(); modalAsk.style.display = "flex"; }); } modalAskClose.addEventListener('click', function() { modalAsk.style.display = "none"; }); } } newsPostAskModal(); function newsPostShareModal() { let shareButton = document.querySelectorAll('.bar-btns__share'); let modalShare = document.querySelector('.modal-share'); let modalShareClose = document.querySelector(".modal-share__form-close"); if (shareButton === null || modalShare === null || modalShareClose === null) { // console.log("askButton left html"); } else { for(let i = 0; i < shareButton.length; i++){ shareButton[i].addEventListener("click", function(e) { e.preventDefault(); modalShare.style.display = "flex"; }); } modalShareClose.addEventListener('click', function() { modalShare.style.display = "none"; }); } } newsPostShareModal(); // modals on vendor-page function vendorPageAskModal() { let askButton = document.querySelector('.single-vendor-description__panel--ask'); let modalAsk = document.querySelector('.modal-ask'); let modalAskClose = document.querySelector('.modal-ask__form-close'); if (askButton === null || modalAsk === null || modalAskClose === null) { // console.log("askButton left html"); }else{ askButton.addEventListener("click", function(e) { e.preventDefault(); modalAsk.style.display = "flex"; }); modalAskClose.addEventListener('click', function() { modalAsk.style.display = "none"; }); } } vendorPageAskModal(); function vendorPageShareModal() { let shareButton = document.querySelector('.single-vendor-description__panel--share'); let modalShare = document.querySelector('.modal-share'); let modalShareClose = document.querySelector(".modal-share__form-close"); if (shareButton === null || modalShare === null || modalShareClose === null) { // console.log("askButton left html"); } else { shareButton.addEventListener("click", function(e) { e.preventDefault(); modalShare.style.display = "flex"; }); modalShareClose.addEventListener('click', function() { modalShare.style.display = "none"; }); } } vendorPageShareModal(); function catalogOffersAskModal() { const bodyContainer = document.querySelector('body'); const modalAskBlur = document.querySelector('.modal-ask__blur'); const modalAskFormActiveState = document.querySelector('.modal-ask__form-inner--done'); const modalAskBtnDone = document.querySelector('.modal-ask__btn--done'); let modalAsk = document.querySelector('.modal-ask'); let catalogAskButtons = document.querySelectorAll('.ask-request'); let modalAskID = document.querySelector('.modal-ask__id b'); let modalAskInputID = document.querySelector('[name="SendQuestionForm[id]"]'); let modalAskInputURL = document.querySelector('[name="SendQuestionForm[url]"]'); let modalAskClose, modalAskInput; let modalAskForm = document.querySelector('.modal-ask__form-inner'); if (catalogAskButtons.length > 0 && modalAsk !== null) { modalAskClose = modalAsk.querySelector('.modal-ask__close'); inputDefaultVal = modalAskInputURL.value; for (let i = 0; i < catalogAskButtons.length; i++) { catalogAskButtons[i].addEventListener('click', function(e) { e.preventDefault(); // modalAskFormActiveState.style.display = 'none'; if (this.dataset.number) { modalAskInputID.value = this.dataset.number; modalAskID.innerText = this.dataset.number; } modalAsk.classList.add('modal-ask--on'); bodyContainer.classList.add('page-body__no-scroll'); modalAskForm.classList.add('modal-ask__form-inner--opening'); }); } // modalAskClose.addEventListener('click', function() { // onModalClose(); // }); // modalAskBlur.addEventListener('click', function() { // onModalClose(); // }); modalAskBtnDone.addEventListener('click', function() { onModalClose(); }); function onModalClose() { modalAskForm.classList.remove('modal-ask__form-inner--opening'); modalAskForm.classList.add('modal-ask__form-inner--closing'); const handleAnimationEnd = function() { modalAsk.classList.remove('modal-ask--on'); modalAskForm.classList.remove('modal-ask__form-inner--closing'); bodyContainer.classList.remove('page-body__no-scroll'); modalAskForm.removeEventListener('animationend', handleAnimationEnd); modalAskInput = modalAsk.getElementsByTagName('input'); for (var i = 0; i < modalAskInput.length; i++) { if (modalAskInput[i].type == "text") { modalAskInput[i].value = ""; } } }; modalAskForm.addEventListener('animationend', handleAnimationEnd); } } } catalogOffersAskModal(); //cookie modal function cookieModalShow(){ let storedCookieLocalStorageParametr = localStorage.getItem('cookiePar'); if(storedCookieLocalStorageParametr === null || storedCookieLocalStorageParametr === 'cookieModalNotSeen'){ localStorage.setItem('cookiePar', 'cookieModalNotSeen'); generateModal(); }else if(storedCookieLocalStorageParametr === 'cookieModalSeen'){ // console.log('cookie modal info have been seen, do nothing :)') } } cookieModalShow(); //create and inject cookie-info modal function generateModal(){ let cookieModal = document.createElement('div'); const body = document.querySelector('.page-body__container'); cookieModal.classList.add('cookie-info-modal'); cookieModal.innerHTML = ` <div class="cookie-info-modal__title">Используем куки</div> <div class="cookie-info-modal__text">Продолжая пользоваться сайтом, вы соглашаетесь на использование <a href="https://final.lr.ru/articles/privacy#private-cookies-scroll-trigger">файлов куки</a></div> <div class="cookie-info-modal__button">Отлично!</div> `; body.appendChild(cookieModal); console.warn(cookieModal) const cookieModalBtn = document.querySelector('.cookie-info-modal__button'); cookieModalBtn.addEventListener('click', function(){ localStorage.setItem('cookiePar', 'cookieModalSeen'); cookieModal.style.display = 'none'; }); } //desktop functions function shopCatalogMechDesktop() { let firstSection = document.querySelector('.shop-catalog-desktop__inner'); let firstTitleOpen = document.querySelector('.shop-catalog-desktop__title-open'); let firstTitleClose = document.querySelector('.shop-catalog-desktop__title-close'); let firstTitleStatic = document.querySelector('.shop-catalog-desktop__title-static'); let firstSectionItems = document.querySelectorAll('.shop-catalog-desktop__item'); firstTitleOpen.style.display = 'none'; firstTitleStatic.style.display = 'block'; let models = document.querySelectorAll('.shop-catalog-desktop__item'); let secondSections = document.querySelectorAll('.shop-catalog-desktop__inner--second'); let secondTitleBlocks = document.querySelectorAll('.shop-catalog-desktop__title--second'); let secondSectionItems = document.querySelectorAll('.shop-catalog-desktop__item--second'); let thirdSections = document.querySelectorAll('.shop-catalog-desktop__inner--third'); let thirdTitleBlocks = document.querySelectorAll('.shop-catalog-desktop__title--third'); let thirdSectionItems = document.querySelectorAll('.shop-catalog-desktop__item--third'); let fourthSections = document.querySelectorAll('.shop-catalog-desktop__inner--fourth'); let fourthTitleBlocks = document.querySelectorAll('.shop-catalog-desktop__title--fourth'); let fourthSectionsItems = document.querySelectorAll('.shop-catalog-desktop__item--fourth'); let fifthSections = document.querySelectorAll('.shop-catalog-desktop__inner--fifth'); let fifthTitleBlocks = document.querySelectorAll('.shop-catalog-desktop__title--fifth'); let fifthSectionsItems = document.querySelectorAll('.shop-catalog-desktop__item--fifth'); let sixthSections = document.querySelectorAll('.shop-catalog-desktop__inner--sixth'); let sixthTitleBlocks = document.querySelectorAll('.shop-catalog-desktop__title--sixth'); let sixthSectionsItems = document.querySelectorAll('.shop-catalog-desktop__item--sixth'); let seventhSections = document.querySelectorAll('.shop-catalog-desktop__inner--seventh'); let seventhTitleBlocks = document.querySelectorAll('.shop-catalog-desktop__title--seventh'); let seventhSectionsItems = document.querySelectorAll('.shop-catalog-desktop__item--seventh'); //Active hover on items/models function activateHoversEachLvlItem(){ for (let i = 0; i < firstSectionItems.length; i++) { let firstItemsTextBlock = firstSectionItems[i].querySelector('.shop-catalog-desktop__item-text'); if(firstItemsTextBlock){ firstSectionItems[i].addEventListener('mouseover', function () { let modelNoOffersBlock = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--model-no-offers'); let itemNoModel = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--no-model'); if(modelNoOffersBlock === null && itemNoModel === null){ firstItemsTextBlock.classList.add('shop-catalog-desktop__item-text--hover'); } }); firstSectionItems[i].addEventListener('mouseout', function () { let modelNoOffersBlock = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--model-no-offers'); let itemNoModel = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--no-model'); if(modelNoOffersBlock === null && itemNoModel === null){ firstItemsTextBlock.classList.remove('shop-catalog-desktop__item-text--hover'); } }); } } for (let i = 0; i < secondSectionItems.length; i++) { let firstItemsTextBlock = secondSectionItems[i].querySelector('.shop-catalog-desktop__item-text'); if(firstItemsTextBlock){ secondSectionItems[i].addEventListener('mouseover', function () { let modelNoOffersBlock = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--model-no-offers'); let itemNoModel = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--no-model'); if(modelNoOffersBlock === null && itemNoModel === null){ firstItemsTextBlock.classList.add('shop-catalog-desktop__item-text--hover'); } }); secondSectionItems[i].addEventListener('mouseout', function () { let modelNoOffersBlock = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--model-no-offers'); let itemNoModel = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--no-model'); if(modelNoOffersBlock === null && itemNoModel === null){ firstItemsTextBlock.classList.remove('shop-catalog-desktop__item-text--hover'); } }); } } for (let i = 0; i < thirdSectionItems.length; i++) { let firstItemsTextBlock = thirdSectionItems[i].querySelector('.shop-catalog-desktop__item-text'); if(firstItemsTextBlock){ thirdSectionItems[i].addEventListener('mouseover', function () { let modelNoOffersBlock = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--model-no-offers'); let itemNoModel = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--no-model'); if(modelNoOffersBlock === null && itemNoModel === null){ firstItemsTextBlock.classList.add('shop-catalog-desktop__item-text--hover'); } }); thirdSectionItems[i].addEventListener('mouseout', function () { let modelNoOffersBlock = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--model-no-offers'); let itemNoModel = firstItemsTextBlock.querySelector('.shop-catalog-desktop__tag-link--no-model'); if(modelNoOffersBlock === null && itemNoModel === null){ firstItemsTextBlock.classList.remove('shop-catalog-desktop__item-text--hover'); } }); } } for (let i = 0; i < fourthSectionsItems.length; i++) { let firstItemsTextBlock = fourthSectionsItems[i].querySelector('.shop-catalog-desktop__item-text'); if(firstItemsTextBlock){ fourthSectionsItems[i].addEventListener('mouseover', function () { firstItemsTextBlock.classList.add('shop-catalog-desktop__item-text--hover'); }); fourthSectionsItems[i].addEventListener('mouseout', function () { firstItemsTextBlock.classList.remove('shop-catalog-desktop__item-text--hover'); }); } } for (let i = 0; i < fifthSectionsItems.length; i++) { let firstItemsTextBlock = fifthSectionsItems[i].querySelector('.shop-catalog-desktop__item-text'); if(firstItemsTextBlock){ fifthSectionsItems[i].addEventListener('mouseover', function () { firstItemsTextBlock.classList.add('shop-catalog-desktop__item-text--hover'); }); fifthSectionsItems[i].addEventListener('mouseout', function () { firstItemsTextBlock.classList.remove('shop-catalog-desktop__item-text--hover'); }); } } for (let i = 0; i < sixthSectionsItems.length; i++) { let firstItemsTextBlock = sixthSectionsItems[i].querySelector('.shop-catalog-desktop__item-text'); if(firstItemsTextBlock){ sixthSectionsItems[i].addEventListener('mouseover', function () { firstItemsTextBlock.classList.add('shop-catalog-desktop__item-text--hover'); }); sixthSectionsItems[i].addEventListener('mouseout', function () { firstItemsTextBlock.classList.remove('shop-catalog-desktop__item-text--hover'); }); } } for (let i = 0; i < seventhSectionsItems.length; i++) { let firstItemsTextBlock = seventhSectionsItems[i].querySelector('.shop-catalog-desktop__item-text'); if(firstItemsTextBlock){ seventhSectionsItems[i].addEventListener('mouseover', function () { firstItemsTextBlock.classList.add('shop-catalog-desktop__item-text--hover'); }); seventhSectionsItems[i].addEventListener('mouseout', function () { firstItemsTextBlock.classList.remove('shop-catalog-desktop__item-text--hover'); }); } } } activateHoversEachLvlItem(); // Click on each Model on the 1 lvl of catalog for (let i = 0; i < models.length; i++) { models[i].addEventListener('click', function (e) { e.preventDefault(); let model = this.querySelector("a"); if(model.classList.contains('final-item')){ console.warn('1 lvl is final'); ShopCatalogDesktopMetaHide(); //clear second title/items defend after repeat function clearSecondTitlesItems(){ secondSections.forEach(item => { item.style.display = 'none'; }); secondTitleBlocks.forEach(item => { item.style.display = 'none'; }); secondSectionItems.forEach(item => { item.style.display = 'none'; }); thirdSections.forEach(item => { item.style.display = 'none'; }); thirdTitleBlocks.forEach(item => { item.style.display = 'none'; }); thirdSectionItems.forEach(item => { item.style.display = 'none'; }); fourthSections.forEach(item => { item.style.display = 'none'; }); fourthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fourthSectionsItems.forEach(item => { item.style.display = 'none'; }); fifthSections.forEach(item => { item.style.display = 'none'; }); fifthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fifthSectionsItems.forEach(item => { item.style.display = 'none'; }); sixthSections.forEach(item => { item.style.display = 'none'; }); sixthTitleBlocks.forEach(item => { item.style.display = 'none'; }); sixthSectionsItems.forEach(item => { item.style.display = 'none'; }); seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearSecondTitlesItems(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear1Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); fifthBlocksClear(); fourthBlocksClear(); thirdBlocksClear(); secondBlocksClear(); modelsClear(); let modelTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(modelTextBlock){ modelTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } shopCatalogDesktopMetaCloser(); }else{ console.warn('1 lvl click') ShopCatalogDesktopMetaHide(); //clear second title/items defend after repeat function clearSecondTitlesItems(){ secondSections.forEach(item => { item.style.display = 'none'; }); secondTitleBlocks.forEach(item => { item.style.display = 'none'; }); secondSectionItems.forEach(item => { item.style.display = 'none'; }); thirdSections.forEach(item => { item.style.display = 'none'; }); thirdTitleBlocks.forEach(item => { item.style.display = 'none'; }); thirdSectionItems.forEach(item => { item.style.display = 'none'; }); fourthSections.forEach(item => { item.style.display = 'none'; }); fourthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fourthSectionsItems.forEach(item => { item.style.display = 'none'; }); fifthSections.forEach(item => { item.style.display = 'none'; }); fifthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fifthSectionsItems.forEach(item => { item.style.display = 'none'; }); sixthSections.forEach(item => { item.style.display = 'none'; }); sixthTitleBlocks.forEach(item => { item.style.display = 'none'; }); sixthSectionsItems.forEach(item => { item.style.display = 'none'; }); seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearSecondTitlesItems(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear1Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); fifthBlocksClear(); fourthBlocksClear(); thirdBlocksClear(); secondBlocksClear(); modelsClear(); //hide stock stockHide(); let modelTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(modelTextBlock){ modelTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } let modelData = model.dataset; secondSections.forEach(item => { if (item.dataset.code == model.dataset.code) { let currentSecondSection = item; currentSecondSection.style.display = 'flex'; currentSecondSection.classList.add('shop-catalog-desktop__inner--second-active'); //Smooth scroll to the proper position setTimeout(() => { const yOffset = -85; const y = currentSecondSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); }, '100'); let titleOfCurrentSecondBlock = currentSecondSection.querySelector('.shop-catalog-desktop__title--second'); let titleOpenOfCurrentSecondBlock = currentSecondSection.querySelector('.shop-catalog-desktop__title-open--second'); let titleCloseOfCurrentSecondBlock = currentSecondSection.querySelector('.shop-catalog-desktop__title-close--second'); let titleStaticCurrentSecondBlock = currentSecondSection.querySelector('.shop-catalog-desktop__title-static--second'); titleOfCurrentSecondBlock.style.display = 'flex'; titleOpenOfCurrentSecondBlock.style.display = 'none'; titleStaticCurrentSecondBlock.style.display = 'block'; firstTitleStatic.style.display = 'none'; firstTitleOpen.style.display = 'flex'; let itemsFromCurrentSecondSection = currentSecondSection.querySelectorAll('.shop-catalog-desktop__item--second'); itemsFromCurrentSecondSection.forEach(item => { item.style.display = 'block'; }); } }); } }); } // Click on each Item on the 2 lvl of catalog for (let i = 0; i < secondSectionItems.length; i++) { secondSectionItems[i].addEventListener('click', function (e) { e.preventDefault(); let secondItem = this.querySelector('a'); if(secondItem.classList.contains('final-item')){ console.warn('2 lvl is final'); ShopCatalogDesktopMetaHide(); //clear second title/items defend after repeat function clearThirdTitlesItems(){ thirdSections.forEach(item => { item.style.display = 'none'; }); thirdTitleBlocks.forEach(item => { item.style.display = 'none'; }); thirdSectionItems.forEach(item => { item.style.display = 'none'; }); fourthSections.forEach(item => { item.style.display = 'none'; }); fourthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fourthSectionsItems.forEach(item => { item.style.display = 'none'; }); fifthSections.forEach(item => { item.style.display = 'none'; }); fifthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fifthSectionsItems.forEach(item => { item.style.display = 'none'; }); sixthSections.forEach(item => { item.style.display = 'none'; }); sixthTitleBlocks.forEach(item => { item.style.display = 'none'; }); sixthSectionsItems.forEach(item => { item.style.display = 'none'; }); seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearThirdTitlesItems(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear2Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); fifthBlocksClear(); fourthBlocksClear(); thirdBlocksClear(); secondBlocksClear(); let secondTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(secondTextBlock){ secondTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } shopCatalogDesktopMetaCloser(); }else{ console.warn('2 lvl click') //clear repeat / re-opened blocks function clearThirdTitlesItems(){ thirdSections.forEach(item => { item.style.display = 'none'; }); thirdTitleBlocks.forEach(item => { item.style.display = 'none'; }); thirdSectionItems.forEach(item => { item.style.display = 'none'; }); fourthSections.forEach(item => { item.style.display = 'none'; }); fourthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fourthSectionsItems.forEach(item => { item.style.display = 'none'; }); fifthSections.forEach(item => { item.style.display = 'none'; }); fifthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fifthSectionsItems.forEach(item => { item.style.display = 'none'; }); sixthSections.forEach(item => { item.style.display = 'none'; }); sixthTitleBlocks.forEach(item => { item.style.display = 'none'; }); sixthSectionsItems.forEach(item => { item.style.display = 'none'; }); seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearThirdTitlesItems(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear2Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); fifthBlocksClear(); fourthBlocksClear(); thirdBlocksClear(); secondBlocksClear(); //hide stock stockHide(); let secondTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(secondTextBlock){ secondTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } thirdSections.forEach(item => { if (item.dataset.code == secondItem.dataset.code) { let currentThirdSection = item; currentThirdSection.style.display = 'flex'; currentThirdSection.classList.add('shop-catalog-desktop__inner--third-active'); //Smooth scroll to the proper position setTimeout(() => { const yOffset = -85; const y = currentThirdSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); }, '100'); let titleOfCurrentThirdBlock = currentThirdSection.querySelector('.shop-catalog-desktop__title--third'); let titleOpenOfCurrentThirdBlock = currentThirdSection.querySelector('.shop-catalog-desktop__title-open--third'); let titleCloseOfCurrentThirdBlock = currentThirdSection.querySelector('.shop-catalog-desktop__title-close--third'); let titleStaticCurrentThirdBlock = currentThirdSection.querySelector('.shop-catalog-desktop__title-static--third'); titleOfCurrentThirdBlock.style.display = 'flex'; titleOpenOfCurrentThirdBlock.style.display = 'none'; titleStaticCurrentThirdBlock.style.display = 'flex'; let itemsFromCurrentThirdSection = currentThirdSection.querySelectorAll('.shop-catalog-desktop__item--third'); itemsFromCurrentThirdSection.forEach(item => { item.style.display = 'block'; }); } }); } }); } // Click on each Item on the 3 lvl of catalog for (let i = 0; i < thirdSectionItems.length; i++) { thirdSectionItems[i].addEventListener('click', function (e) { e.preventDefault(); let thirdItem = this.querySelector('a'); if(thirdItem.classList.contains('final-item')){ console.warn('3 lvl is final'); function clearfourthTitlesItems(){ fourthSections.forEach(item => { item.style.display = 'none'; }); fourthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fourthSectionsItems.forEach(item => { item.style.display = 'none'; }); fifthSections.forEach(item => { item.style.display = 'none'; }); fifthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fifthSectionsItems.forEach(item => { item.style.display = 'none'; }); sixthSections.forEach(item => { item.style.display = 'none'; }); sixthTitleBlocks.forEach(item => { item.style.display = 'none'; }); sixthSectionsItems.forEach(item => { item.style.display = 'none'; }); seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearfourthTitlesItems(); function innerBlocksActivesClear3Stage(){ fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear3Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); fifthBlocksClear(); fourthBlocksClear(); thirdBlocksClear(); shopCatalogDesktopMetaCloser(); let thirdTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(thirdTextBlock){ thirdTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } }else{ console.warn('3 lvl click') function clearfourthTitlesItems(){ fourthSections.forEach(item => { item.style.display = 'none'; }); fourthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fourthSectionsItems.forEach(item => { item.style.display = 'none'; }); fifthSections.forEach(item => { item.style.display = 'none'; }); fifthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fifthSectionsItems.forEach(item => { item.style.display = 'none'; }); sixthSections.forEach(item => { item.style.display = 'none'; }); sixthTitleBlocks.forEach(item => { item.style.display = 'none'; }); sixthSectionsItems.forEach(item => { item.style.display = 'none'; }); seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearfourthTitlesItems(); function innerBlocksActivesClear3Stage(){ fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear3Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); fifthBlocksClear(); fourthBlocksClear(); thirdBlocksClear(); //hide stock stockHide(); // titleStaticCurrentThirdBlock.style.display = 'none'; // titleOpenOfCurrentThirdBlock.style.display = 'flex'; let thirdTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(thirdTextBlock){ thirdTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } fourthSections.forEach(item => { if (item.dataset.code == thirdItem.dataset.code) { let currentFourthSection = item; currentFourthSection.style.display = 'flex'; currentFourthSection.classList.add('shop-catalog-desktop__inner--fourth-active'); //Smooth scroll to the proper position setTimeout(() => { const yOffset = -85; const y = currentFourthSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); }, '100'); let titleOfCurrentFourthBlock = currentFourthSection.querySelector('.shop-catalog-desktop__title--fourth'); let titleOpenOfCurrentFourthBlock = currentFourthSection.querySelector('.shop-catalog-desktop__title-open--fourth'); let titleCloseOfCurrentFourthBlock = currentFourthSection.querySelector('.shop-catalog-desktop__title-close--fourth'); titleOfCurrentFourthBlock.style.display = 'flex'; let itemsFromCurrentFourthSection = currentFourthSection.querySelectorAll('.shop-catalog-desktop__item--fourth'); itemsFromCurrentFourthSection.forEach(item => { item.style.display = 'block'; }); } }); } }); } // Click on each Item on the 4 lvl of catalog for (let i = 0; i < fourthSectionsItems.length; i++) { fourthSectionsItems[i].addEventListener('click', function (e) { e.preventDefault(); let fourthItem = this.querySelector('a'); if(fourthItem.classList.contains('final-item')){ console.warn('4 lvl is final'); function clearFifthTitlesItems(){ fifthSections.forEach(item => { item.style.display = 'none'; }); fifthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fifthSectionsItems.forEach(item => { item.style.display = 'none'; }); sixthSections.forEach(item => { item.style.display = 'none'; }); sixthTitleBlocks.forEach(item => { item.style.display = 'none'; }); sixthSectionsItems.forEach(item => { item.style.display = 'none'; }); seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearFifthTitlesItems(); function innerBlocksActivesClear4Stage(){ fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear4Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); fifthBlocksClear(); fourthBlocksClear(); let fourthTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(fourthTextBlock){ fourthTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } shopCatalogDesktopMetaCloser(); }else{ console.warn('4 lvl click') //clear repeat / re-opened blocks function clearFifthTitlesItems(){ fifthSections.forEach(item => { item.style.display = 'none'; }); fifthTitleBlocks.forEach(item => { item.style.display = 'none'; }); fifthSectionsItems.forEach(item => { item.style.display = 'none'; }); sixthSections.forEach(item => { item.style.display = 'none'; }); sixthTitleBlocks.forEach(item => { item.style.display = 'none'; }); sixthSectionsItems.forEach(item => { item.style.display = 'none'; }); seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearFifthTitlesItems(); function innerBlocksActivesClear4Stage(){ fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear4Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); fifthBlocksClear(); fourthBlocksClear(); //hide stock stockHide(); let fourthTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(fourthTextBlock){ fourthTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } fifthSections.forEach(item => { if (item.dataset.code == fourthItem.dataset.code) { let currentFifthSection = item; currentFifthSection.style.display = 'flex'; currentFifthSection.classList.add('shop-catalog-desktop__inner--fifth-active'); //Smooth scroll to the proper position setTimeout(() => { const yOffset = -85; const y = currentFifthSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); }, '100'); let titleOfCurrentFifthBlock = currentFifthSection.querySelector('.shop-catalog-desktop__title--fifth'); let titleOpenOfCurrentFifthBlock = currentFifthSection.querySelector('.shop-catalog-desktop__title-open--fifth'); let titleCloseOfCurrentFifthBlock = currentFifthSection.querySelector('.shop-catalog-desktop__title-close--fifth'); titleOfCurrentFifthBlock.style.display = 'flex'; let itemsFromCurrentFifthSection = currentFifthSection.querySelectorAll('.shop-catalog-desktop__item--fifth'); itemsFromCurrentFifthSection.forEach(item => { item.style.display = 'block'; }); } }); } }); } // Click on each Item on the 5 lvl of catalog for (let i = 0; i < fifthSectionsItems.length; i++) { fifthSectionsItems[i].addEventListener('click', function (e) { e.preventDefault(); let fifthItem = this.querySelector('a'); if(fifthItem.classList.contains('final-item')){ console.warn('5 lvl is final'); //clear repeat / re-opened blocks function clearSixthTitlesItems(){ sixthSections.forEach(item => { item.style.display = 'none'; }); sixthTitleBlocks.forEach(item => { item.style.display = 'none'; }); sixthSectionsItems.forEach(item => { item.style.display = 'none'; }); seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearSixthTitlesItems(); function innerBlocksActivesClear5Stage(){ sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear5Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); fifthBlocksClear(); let fifthTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(fifthTextBlock){ fifthTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } shopCatalogDesktopMetaCloser(); }else{ console.warn('5 lvl click') //clear repeat / re-opened blocks function clearSixthTitlesItems(){ sixthSections.forEach(item => { item.style.display = 'none'; }); sixthTitleBlocks.forEach(item => { item.style.display = 'none'; }); sixthSectionsItems.forEach(item => { item.style.display = 'none'; }); seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearSixthTitlesItems(); function innerBlocksActivesClear5Stage(){ sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear5Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); fifthBlocksClear(); //hide stock stockHide(); let fifthTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(fifthTextBlock){ fifthTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } sixthSections.forEach(item => { if (item.dataset.code == fifthItem.dataset.code) { let currentSixthSection = item; currentSixthSection.style.display = 'flex'; currentSixthSection.classList.add('shop-catalog-desktop__inner--sixth-active'); //Smooth scroll to the proper position setTimeout(() => { const yOffset = -85; const y = currentSixthSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); }, '100'); let titleOfCurrentSixthBlock = currentSixthSection.querySelector('.shop-catalog-desktop__title--sixth'); let titleOpenOfCurrentSixthBlock = currentSixthSection.querySelector('.shop-catalog-desktop__title-open--sixth'); let titleCloseOfCurrentSixthBlock = currentSixthSection.querySelector('.shop-catalog-desktop__title-close--sixth'); titleOfCurrentSixthBlock.style.display = 'flex'; let itemsFromCurrentSixthSection = currentSixthSection.querySelectorAll('.shop-catalog-desktop__item--sixth'); itemsFromCurrentSixthSection.forEach(item => { item.style.display = 'block'; }); } }); } }); } // Click on each Item on the 6 lvl of catalog for (let i = 0; i < sixthSectionsItems.length; i++) { sixthSectionsItems[i].addEventListener('click', function (e) { e.preventDefault(); let sixthItem = this.querySelector('a'); if(sixthItem.classList.contains('final-item')){ console.warn('6 lvl is final'); //clear repeat / re-opened blocks function clearSeventhTitlesItems(){ seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearSeventhTitlesItems(); function innerBlocksActivesClear6Stage(){ seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear6Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); let sixthTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(sixthTextBlock){ sixthTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } shopCatalogDesktopMetaCloser(); }else{ console.warn('6 lvl click'); //clear repeat / re-opened blocks function clearSeventhTitlesItems(){ seventhSections.forEach(item => { item.style.display = 'none'; }); seventhTitleBlocks.forEach(item => { item.style.display = 'none'; }); seventhSectionsItems.forEach(item => { item.style.display = 'none'; }); } clearSeventhTitlesItems(); function innerBlocksActivesClear6Stage(){ seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--seventh-active'); }); } innerBlocksActivesClear6Stage(); clearLastOfferData(); seventhBlocksClear(); sixthBlocksClear(); //hide stock stockHide(); let sixthTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(sixthTextBlock){ sixthTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } seventhSections.forEach(item => { if (item.dataset.code == sixthItem.dataset.code) { let currentSeventhSection = item; currentSeventhSection.style.display = 'flex'; currentSeventhSection.classList.add('shop-catalog-desktop__inner--seventh-active'); //Smooth scroll to the proper position setTimeout(() => { const yOffset = -85; const y = currentSeventhSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); }, '100'); let titleOfCurrentSeventhBlock = currentSeventhSection.querySelector('.shop-catalog-desktop__title--seventh'); let titleOpenOfCurrentSeventhBlock = currentSeventhSection.querySelector('.shop-catalog-desktop__title-open--seventh'); let titleCloseOfCurrentSeventhBlock = currentSeventhSection.querySelector('.shop-catalog-desktop__title-close--seventh'); titleOfCurrentSeventhBlock.style.display = 'flex'; let itemsFromCurrentSeventhSection = currentSeventhSection.querySelectorAll('.shop-catalog-desktop__item--seventh'); itemsFromCurrentSeventhSection.forEach(item => { item.style.display = 'block'; }); } }); } }); } // Click on each Item on the 7 lvl of catalog || ONLY FINAL for (let i = 0; i < seventhSectionsItems.length; i++) { seventhSectionsItems[i].addEventListener('click', function (e) { e.preventDefault(); console.warn('7 lvl is final'); //clear repeat / re-opened blocks let seventhItem = this.querySelector('a'); let seventhTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(seventhTextBlock){ seventhTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } clearLastOfferData(); seventhBlocksClear(); shopCatalogDesktopMetaCloser(); }); } } function shopCatalogDynamicUrlDesktop(){ let firstItems = document.querySelectorAll('.shop-catalog-desktop__item'); let secondSectionItems = document.querySelectorAll('.shop-catalog-desktop__item--second'); let thirdSectionItems = document.querySelectorAll('.shop-catalog-desktop__item--third'); let fourthSectionItems = document.querySelectorAll('.shop-catalog-desktop__item--fourth'); let fifthSectionItems = document.querySelectorAll('.shop-catalog-desktop__item--fifth'); let sixthSectionItems = document.querySelectorAll('.shop-catalog-desktop__item--sixth'); firstItems.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-desktop__item-text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelTextCapitalized}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); secondSectionItems.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-desktop__item-text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelTextCapitalized}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); thirdSectionItems.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-desktop__item-text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelText}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); fourthSectionItems.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-desktop__item-text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelText}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); fifthSectionItems.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-desktop__item-text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelText}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); sixthSectionItems.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-desktop__item-text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelText}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); } shopCatalogDynamicUrlDesktop(); function shopCatalogDynamicUrlMobile(){ let modelsMobile = document.querySelectorAll('.shop-catalog-mobile-item'); let secondSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--second'); let thirdSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--third'); let fourthSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--fourth'); let fifthSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--fifth'); let sixthSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--sixth'); let seventhSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--seventh'); modelsMobile.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-mobile-item__text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelTextCapitalized}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); secondSectionItemsMobile.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-mobile-item__text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelTextCapitalized}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); thirdSectionItemsMobile.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-mobile-item__text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelTextCapitalized}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); fourthSectionItemsMobile.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-mobile-item__text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelTextCapitalized}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); fifthSectionItemsMobile.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-mobile-item__text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelTextCapitalized}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); sixthSectionItemsMobile.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-mobile-item__text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelTextCapitalized}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); seventhSectionItemsMobile.forEach(item => { item.addEventListener('click', function(){ let modelLink = item.querySelector('a').href; let modelText = item.querySelector('.shop-catalog-mobile-item__text').innerText; let modelTextLowerCase = modelText.toLowerCase(); let modelTextCapitalized = modelTextLowerCase.charAt(0).toUpperCase() + modelTextLowerCase.slice(1); let newTitleForBrowser = `LR.RU - ${modelTextCapitalized}` window.history.pushState({}, newTitleForBrowser, modelLink); document.title = newTitleForBrowser; }); }); } shopCatalogDynamicUrlMobile(); function shopCatalogDesktopMetaCloser(){ const firstSection = document.querySelector('.shop-catalog-desktop__inner'); const innerSecondActive = document.querySelector('.shop-catalog-desktop__inner--second-active'); const innerThirdActive = document.querySelector('.shop-catalog-desktop__inner--third-active'); const innerFourthActive = document.querySelector('.shop-catalog-desktop__inner--fourth-active'); const innerFifthActive = document.querySelector('.shop-catalog-desktop__inner--fifth-active'); const innerSixthActive = document.querySelector('.shop-catalog-desktop__inner--sixth-active'); const innerSeventhActive = document.querySelector('.shop-catalog-desktop__inner--seventh-active'); const finalItemActive = document.querySelector('.final-item--active'); let intViewportWidth = window.innerWidth; const shopCatalogParent = document.querySelector('.shop-catalog-desktop'); let secondSections = document.querySelectorAll('.shop-catalog-desktop__inner--second'); let thirdSections = document.querySelectorAll('.shop-catalog-desktop__inner--third'); let fourthSections = document.querySelectorAll('.shop-catalog-desktop__inner--fourth'); let fifthSections = document.querySelectorAll('.shop-catalog-desktop__inner--fifth'); let sixthSections = document.querySelectorAll('.shop-catalog-desktop__inner--sixth'); let seventhSections = document.querySelectorAll('.shop-catalog-desktop__inner--seventh'); if(innerSeventhActive){ // console.warn('7lvl meta to go'); //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-desktop__title--third'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-desktop__title--fourth'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-desktop__title--fifth'); const innerSixthActiveTitle = innerSixthActive.querySelector('.shop-catalog-desktop__title--sixth'); const innerSeventhActiveTitle = innerSeventhActive.querySelector('.shop-catalog-desktop__title--seventh'); //CLONE First Meta Title let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //CLONE Third Meta Title const thirdActiveTitleMeta = innerThirdActiveTitle.cloneNode(true); thirdActiveTitleMeta.classList.add('shop-catalog-desktop__title--third-meta'); //Transform to OPEN Phase const innerThirdMetaTitleStaticBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--third'); const innerThirdMetaTitleOpenBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--third'); innerThirdMetaTitleStaticBlock.style.display = 'none'; innerThirdMetaTitleOpenBlock.style.display = 'block'; // Clone Fourth Meta Title let fourthActiveTitleMeta = innerFourthActiveTitle.cloneNode(true); fourthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fourth-meta'); //Transform to OPEN Phase const innerFourthMetaTitleStaticBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--fourth'); const innerFourthMetaTitleOpenBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fourth'); // innerFourthMetaTitleStaticBlock.style.display = 'none'; innerFourthMetaTitleOpenBlock.style.display = 'block'; // Clone Fifth Meta Title let fifthActiveTitleMeta = innerFifthActiveTitle.cloneNode(true); fifthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fifth-meta'); const innerFifthMetaTitleOpenBlock = fifthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fifth'); // Clone Sixth Meta Title let sixthActiveTitleMeta = innerSixthActiveTitle.cloneNode(true); sixthActiveTitleMeta.classList.add('shop-catalog-desktop__title--sixth-meta'); const innerSixthMetaTitleOpenBlock = sixthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--sixth'); // Clone Sixth Meta Title let seventhActiveTitleMeta = innerSeventhActiveTitle.cloneNode(true); seventhActiveTitleMeta.classList.add('shop-catalog-desktop__title--seventh-meta'); const innerSeventhMetaTitleOpenBlock = seventhActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--seventh'); //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(thirdActiveTitleMeta); metaInner.append(fourthActiveTitleMeta); metaInner.append(fifthActiveTitleMeta); metaInner.append(sixthActiveTitleMeta); metaInner.append(seventhActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; innerSixthActive.style.display = 'none'; innerSeventhActive.style.display = 'none'; //Now OPEN firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear2Stage(); }); thirdActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear3Stage(){ fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear3Stage(); }); fourthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear4Stage(){ fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear4Stage(); }); fifthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear5Stage(){ sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear5Stage(); }); sixthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; innerSixthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSixthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear5Stage(){ seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear5Stage(); }); seventhActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; innerSixthActive.style.display = 'flex'; innerSeventhActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSeventhActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); }); }else if(innerSixthActive){ //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); // console.warn('6lvl meta to go'); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-desktop__title--third'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-desktop__title--fourth'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-desktop__title--fifth'); const innerSixthActiveTitle = innerSixthActive.querySelector('.shop-catalog-desktop__title--sixth'); //CLONE First Meta Title let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //CLONE Third Meta Title const thirdActiveTitleMeta = innerThirdActiveTitle.cloneNode(true); thirdActiveTitleMeta.classList.add('shop-catalog-desktop__title--third-meta'); //Transform to OPEN Phase const innerThirdMetaTitleStaticBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--third'); const innerThirdMetaTitleOpenBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--third'); innerThirdMetaTitleStaticBlock.style.display = 'none'; innerThirdMetaTitleOpenBlock.style.display = 'block'; // Clone Fourth Meta Title let fourthActiveTitleMeta = innerFourthActiveTitle.cloneNode(true); fourthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fourth-meta'); //Transform to OPEN Phase const innerFourthMetaTitleStaticBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--fourth'); const innerFourthMetaTitleOpenBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fourth'); // innerFourthMetaTitleStaticBlock.style.display = 'none'; innerFourthMetaTitleOpenBlock.style.display = 'block'; // Clone Fifth Meta Title let fifthActiveTitleMeta = innerFifthActiveTitle.cloneNode(true); fifthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fifth-meta'); const innerFifthMetaTitleOpenBlock = fifthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fifth'); // Clone Fifth Meta Title let sixthActiveTitleMeta = innerSixthActiveTitle.cloneNode(true); sixthActiveTitleMeta.classList.add('shop-catalog-desktop__title--sixth-meta'); const innerSixthMetaTitleOpenBlock = sixthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--sixth'); //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(thirdActiveTitleMeta); metaInner.append(fourthActiveTitleMeta); metaInner.append(fifthActiveTitleMeta); metaInner.append(sixthActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; innerSixthActive.style.display = 'none'; //Now OPEN firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear2Stage(); }); thirdActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear3Stage(){ fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear3Stage(); }); fourthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear4Stage(){ fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear4Stage(); }); fifthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear5Stage(){ sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear5Stage(); }); sixthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; innerSixthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSixthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); }); }else if(innerFifthActive){ //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); // console.warn('5lvl meta to go'); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-desktop__title--third'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-desktop__title--fourth'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-desktop__title--fifth'); //CLONE First Meta Title let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //CLONE Third Meta Title const thirdActiveTitleMeta = innerThirdActiveTitle.cloneNode(true); thirdActiveTitleMeta.classList.add('shop-catalog-desktop__title--third-meta'); //Transform to OPEN Phase const innerThirdMetaTitleStaticBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--third'); const innerThirdMetaTitleOpenBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--third'); innerThirdMetaTitleStaticBlock.style.display = 'none'; innerThirdMetaTitleOpenBlock.style.display = 'block'; // Clone Fourth Meta Title let fourthActiveTitleMeta = innerFourthActiveTitle.cloneNode(true); fourthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fourth-meta'); //Transform to OPEN Phase const innerFourthMetaTitleStaticBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--fourth'); const innerFourthMetaTitleOpenBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fourth'); // innerFourthMetaTitleStaticBlock.style.display = 'none'; innerFourthMetaTitleOpenBlock.style.display = 'block'; // Clone Fifth Meta Title let fifthActiveTitleMeta = innerFifthActiveTitle.cloneNode(true); fifthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fifth-meta'); const innerFifthMetaTitleOpenBlock = fifthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fifth'); //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(thirdActiveTitleMeta); metaInner.append(fourthActiveTitleMeta); metaInner.append(fifthActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; //Now OPEN firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); } innerBlocksActivesClear2Stage(); }); thirdActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear3Stage(){ fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); } innerBlocksActivesClear3Stage(); }); fourthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear3Stage(){ fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); } innerBlocksActivesClear3Stage(); }); fifthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); }); }else if(innerFourthActive){ //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); // console.warn('4lvl meta to go'); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-desktop__title--third'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-desktop__title--fourth'); //CLONE First Meta Title let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //CLONE Third Meta Title const thirdActiveTitleMeta = innerThirdActiveTitle.cloneNode(true); thirdActiveTitleMeta.classList.add('shop-catalog-desktop__title--third-meta'); //Transform to OPEN Phase const innerThirdMetaTitleStaticBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--third'); const innerThirdMetaTitleOpenBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--third'); innerThirdMetaTitleStaticBlock.style.display = 'none'; innerThirdMetaTitleOpenBlock.style.display = 'block'; // Clone Fourth Meta Title let fourthActiveTitleMeta = innerFourthActiveTitle.cloneNode(true); fourthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fourth-meta'); //Transform to OPEN Phase // const innerFourthMetaTitleStaticBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--fourth'); const innerFourthMetaTitleOpenBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fourth'); // innerFourthMetaTitleStaticBlock.style.display = 'none'; innerFourthMetaTitleOpenBlock.style.display = 'block'; //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; // console.warn(secondActiveTitleMeta); // console.warn(shopCatalogInnerThirdActiveTitleMeta); let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(thirdActiveTitleMeta); metaInner.append(fourthActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; //Now OPEN //First level firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear2Stage(); }); thirdActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear3Stage(){ fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); } innerBlocksActivesClear3Stage(); }); fourthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); }); }else if(innerThirdActive){ //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); // console.warn('3lvl meta to go'); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-desktop__title--third'); //CLONE First Meta Title let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //CLONE Third Meta Title const thirdActiveTitleMeta = innerThirdActiveTitle.cloneNode(true); thirdActiveTitleMeta.classList.add('shop-catalog-desktop__title--third-meta'); //Transform to OPEN Phase const innerThirdMetaTitleStaticBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--third'); const innerThirdMetaTitleOpenBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--third'); innerThirdMetaTitleStaticBlock.style.display = 'none'; innerThirdMetaTitleOpenBlock.style.display = 'block'; //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; // console.warn(secondActiveTitleMeta); // console.warn(shopCatalogInnerThirdActiveTitleMeta); let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(thirdActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; //Now OPEN //First level firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear2Stage(); }); thirdActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); }); }else if(innerThirdActive === null && innerFourthActive === null && innerSecondActive != null){ // console.warn('2lvl meta to go'); //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); if(innerSecondActive){ //CLONE First Meta Title const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; // console.warn(secondActiveTitleMeta); // console.warn(shopCatalogInnerThirdActiveTitleMeta); let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; //Now OPEN //First level firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear2Stage(); }); } }else if(innerThirdActive === null && innerFourthActive === null && innerSecondActive === null){ console.warn('1lvl meta to go'); firstSection.style.display = 'flex'; const yOffset = -70; const y = firstSection.getBoundingClientRect().bottom + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); } } //MetaCloser when link-onloaded function shopCatalogDesktopMetaCloserFromLink(){ let firstSection = document.querySelector('.shop-catalog-desktop__inner'); let intViewportWidth = window.innerWidth; if(intViewportWidth > 1140){ if(firstSection){ const innerSeconds = document.querySelectorAll('.shop-catalog-desktop__inner--second'); const innerThirds = document.querySelectorAll('.shop-catalog-desktop__inner--third'); const innerFourth = document.querySelectorAll('.shop-catalog-desktop__inner--fourth'); const innerFifth = document.querySelectorAll('.shop-catalog-desktop__inner--fifth'); const innerSixth = document.querySelectorAll('.shop-catalog-desktop__inner--sixth'); const innerSeventh = document.querySelectorAll('.shop-catalog-desktop__inner--seventh'); let secondSections = document.querySelectorAll('.shop-catalog-desktop__inner--second'); let thirdSections = document.querySelectorAll('.shop-catalog-desktop__inner--third'); let fourthSections = document.querySelectorAll('.shop-catalog-desktop__inner--fourth'); let fifthSections = document.querySelectorAll('.shop-catalog-desktop__inner--fifth'); let sixthSections = document.querySelectorAll('.shop-catalog-desktop__inner--sixth'); let seventhSections = document.querySelectorAll('.shop-catalog-desktop__inner--seventh'); const shopCatalogParent = document.querySelector('.catalog__departament'); const finalItemActiveWithActiveTextBlock = document.querySelector('.final-item .shop-catalog-desktop__item-text--active'); if(finalItemActiveWithActiveTextBlock){ const finalItemActive = finalItemActiveWithActiveTextBlock.closest('.final-item'); //Smooth scroll to the proper position const yOffset = -10; const y = shopCatalogParent.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); //find active/visible seventh block here innerSeventh.forEach(item => { if(window.getComputedStyle(item).display == 'flex'){ item.classList.add('shop-catalog-desktop__inner--seventh-active'); } }); //find active/visible sixth block here innerSixth.forEach(item => { if(window.getComputedStyle(item).display == 'flex'){ item.classList.add('shop-catalog-desktop__inner--sixth-active'); } }); //find active/visible fifth block here innerFifth.forEach(item => { if(window.getComputedStyle(item).display == 'flex'){ item.classList.add('shop-catalog-desktop__inner--fifth-active'); } }); //find active/visible fourth block here innerFourth.forEach(item => { if(window.getComputedStyle(item).display == 'flex'){ item.classList.add('shop-catalog-desktop__inner--fourth-active'); } }); //find active/visible thirds block here innerThirds.forEach(item => { if(window.getComputedStyle(item).display == 'flex'){ item.classList.add('shop-catalog-desktop__inner--third-active'); } }); //find active/visible second block here innerSeconds.forEach(item => { if(window.getComputedStyle(item).display == 'flex'){ item.classList.add('shop-catalog-desktop__inner--second-active'); } }); //then generate pre meta block const innerSecondActive = document.querySelector('.shop-catalog-desktop__inner--second-active'); const innerThirdActive = document.querySelector('.shop-catalog-desktop__inner--third-active'); const innerFourthActive = document.querySelector('.shop-catalog-desktop__inner--fourth-active'); const innerFifthActive = document.querySelector('.shop-catalog-desktop__inner--fifth-active'); const innerSixthActive = document.querySelector('.shop-catalog-desktop__inner--sixth-active'); const innerSeventhActive = document.querySelector('.shop-catalog-desktop__inner--seventh-active'); //**** if(innerSeventhActive){ console.warn('7lvl meta to go FROM LINK'); //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-desktop__title--third'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-desktop__title--fourth'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-desktop__title--fifth'); const innerSixthActiveTitle = innerSixthActive.querySelector('.shop-catalog-desktop__title--sixth'); const innerSeventhActiveTitle = innerSeventhActive.querySelector('.shop-catalog-desktop__title--seventh'); //CLONE First Meta Title let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //CLONE Third Meta Title const thirdActiveTitleMeta = innerThirdActiveTitle.cloneNode(true); thirdActiveTitleMeta.classList.add('shop-catalog-desktop__title--third-meta'); //Transform to OPEN Phase const innerThirdMetaTitleStaticBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--third'); const innerThirdMetaTitleOpenBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--third'); innerThirdMetaTitleStaticBlock.style.display = 'none'; innerThirdMetaTitleOpenBlock.style.display = 'block'; // Clone Fourth Meta Title let fourthActiveTitleMeta = innerFourthActiveTitle.cloneNode(true); fourthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fourth-meta'); //Transform to OPEN Phase const innerFourthMetaTitleStaticBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--fourth'); const innerFourthMetaTitleOpenBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fourth'); // innerFourthMetaTitleStaticBlock.style.display = 'none'; innerFourthMetaTitleOpenBlock.style.display = 'block'; // Clone Fifth Meta Title let fifthActiveTitleMeta = innerFifthActiveTitle.cloneNode(true); fifthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fifth-meta'); const innerFifthMetaTitleOpenBlock = fifthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fifth'); // Clone Sixth Meta Title let sixthActiveTitleMeta = innerSixthActiveTitle.cloneNode(true); sixthActiveTitleMeta.classList.add('shop-catalog-desktop__title--sixth-meta'); const innerSixthMetaTitleOpenBlock = sixthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--sixth'); // Clone Sixth Meta Title let seventhActiveTitleMeta = innerSeventhActiveTitle.cloneNode(true); seventhActiveTitleMeta.classList.add('shop-catalog-desktop__title--seventh-meta'); const innerSeventhMetaTitleOpenBlock = seventhActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--seventh'); //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(thirdActiveTitleMeta); metaInner.append(fourthActiveTitleMeta); metaInner.append(fifthActiveTitleMeta); metaInner.append(sixthActiveTitleMeta); metaInner.append(seventhActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; innerSixthActive.style.display = 'none'; innerSeventhActive.style.display = 'none'; //Now OPEN firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear2Stage(); }); thirdActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear3Stage(){ fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear3Stage(); }); fourthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear4Stage(){ fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear4Stage(); }); fifthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear5Stage(){ sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear5Stage(); }); sixthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; innerSixthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSixthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear5Stage(){ seventhSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear5Stage(); }); seventhActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; innerSixthActive.style.display = 'flex'; innerSeventhActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSeventhActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); }); }else if(innerSixthActive){ //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); console.warn('6lvl meta to go FROM LINK'); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-desktop__title--third'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-desktop__title--fourth'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-desktop__title--fifth'); const innerSixthActiveTitle = innerSixthActive.querySelector('.shop-catalog-desktop__title--sixth'); //CLONE First Meta Title let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //CLONE Third Meta Title const thirdActiveTitleMeta = innerThirdActiveTitle.cloneNode(true); thirdActiveTitleMeta.classList.add('shop-catalog-desktop__title--third-meta'); //Transform to OPEN Phase const innerThirdMetaTitleStaticBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--third'); const innerThirdMetaTitleOpenBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--third'); innerThirdMetaTitleStaticBlock.style.display = 'none'; innerThirdMetaTitleOpenBlock.style.display = 'block'; // Clone Fourth Meta Title let fourthActiveTitleMeta = innerFourthActiveTitle.cloneNode(true); fourthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fourth-meta'); //Transform to OPEN Phase const innerFourthMetaTitleStaticBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--fourth'); const innerFourthMetaTitleOpenBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fourth'); // innerFourthMetaTitleStaticBlock.style.display = 'none'; innerFourthMetaTitleOpenBlock.style.display = 'block'; // Clone Fifth Meta Title let fifthActiveTitleMeta = innerFifthActiveTitle.cloneNode(true); fifthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fifth-meta'); const innerFifthMetaTitleOpenBlock = fifthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fifth'); // Clone Fifth Meta Title let sixthActiveTitleMeta = innerSixthActiveTitle.cloneNode(true); sixthActiveTitleMeta.classList.add('shop-catalog-desktop__title--sixth-meta'); const innerSixthMetaTitleOpenBlock = sixthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--sixth'); //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(thirdActiveTitleMeta); metaInner.append(fourthActiveTitleMeta); metaInner.append(fifthActiveTitleMeta); metaInner.append(sixthActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; innerSixthActive.style.display = 'none'; //Now OPEN firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear2Stage(); }); thirdActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear3Stage(){ fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear3Stage(); }); fourthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear4Stage(){ fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear4Stage(); }); fifthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear5Stage(){ sixthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--sixth-active'); }); } innerBlocksActivesClear5Stage(); }); sixthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; innerSixthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSixthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); }); }else if(innerFifthActive){ //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); console.warn('5lvl meta to go FROM LINK'); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-desktop__title--third'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-desktop__title--fourth'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-desktop__title--fifth'); //CLONE First Meta Title let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //CLONE Third Meta Title const thirdActiveTitleMeta = innerThirdActiveTitle.cloneNode(true); thirdActiveTitleMeta.classList.add('shop-catalog-desktop__title--third-meta'); //Transform to OPEN Phase const innerThirdMetaTitleStaticBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--third'); const innerThirdMetaTitleOpenBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--third'); innerThirdMetaTitleStaticBlock.style.display = 'none'; innerThirdMetaTitleOpenBlock.style.display = 'block'; // Clone Fourth Meta Title let fourthActiveTitleMeta = innerFourthActiveTitle.cloneNode(true); fourthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fourth-meta'); //Transform to OPEN Phase const innerFourthMetaTitleStaticBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--fourth'); const innerFourthMetaTitleOpenBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fourth'); // innerFourthMetaTitleStaticBlock.style.display = 'none'; innerFourthMetaTitleOpenBlock.style.display = 'block'; // Clone Fifth Meta Title let fifthActiveTitleMeta = innerFifthActiveTitle.cloneNode(true); fifthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fifth-meta'); const innerFifthMetaTitleOpenBlock = fifthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fifth'); //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(thirdActiveTitleMeta); metaInner.append(fourthActiveTitleMeta); metaInner.append(fifthActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; //Now OPEN firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); } innerBlocksActivesClear2Stage(); }); thirdActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear3Stage(){ fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); } innerBlocksActivesClear3Stage(); }); fourthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear3Stage(){ fifthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fifth-active'); }); } innerBlocksActivesClear3Stage(); }); fifthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; innerFifthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); }); }else if(innerFourthActive){ //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); console.warn('4lvl meta to go FROM LINK'); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-desktop__title--third'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-desktop__title--fourth'); //CLONE First Meta Title let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //CLONE Third Meta Title const thirdActiveTitleMeta = innerThirdActiveTitle.cloneNode(true); thirdActiveTitleMeta.classList.add('shop-catalog-desktop__title--third-meta'); //Transform to OPEN Phase const innerThirdMetaTitleStaticBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--third'); const innerThirdMetaTitleOpenBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--third'); innerThirdMetaTitleStaticBlock.style.display = 'none'; innerThirdMetaTitleOpenBlock.style.display = 'block'; // Clone Fourth Meta Title let fourthActiveTitleMeta = innerFourthActiveTitle.cloneNode(true); fourthActiveTitleMeta.classList.add('shop-catalog-desktop__title--fourth-meta'); //Transform to OPEN Phase // const innerFourthMetaTitleStaticBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--fourth'); const innerFourthMetaTitleOpenBlock = fourthActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--fourth'); // innerFourthMetaTitleStaticBlock.style.display = 'none'; innerFourthMetaTitleOpenBlock.style.display = 'block'; //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; // console.warn(secondActiveTitleMeta); // console.warn(shopCatalogInnerThirdActiveTitleMeta); let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(thirdActiveTitleMeta); metaInner.append(fourthActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; //Now OPEN //First level firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear2Stage(); }); thirdActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear3Stage(){ fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); } innerBlocksActivesClear3Stage(); }); fourthActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; innerFourthActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); }); }else if(innerThirdActive){ //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); console.warn('3lvl meta to go FROM LINK'); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-desktop__title--third'); //CLONE First Meta Title let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //CLONE Third Meta Title const thirdActiveTitleMeta = innerThirdActiveTitle.cloneNode(true); thirdActiveTitleMeta.classList.add('shop-catalog-desktop__title--third-meta'); //Transform to OPEN Phase const innerThirdMetaTitleStaticBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--third'); const innerThirdMetaTitleOpenBlock = thirdActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--third'); innerThirdMetaTitleStaticBlock.style.display = 'none'; innerThirdMetaTitleOpenBlock.style.display = 'block'; //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; // console.warn(secondActiveTitleMeta); // console.warn(shopCatalogInnerThirdActiveTitleMeta); let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(thirdActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; //Now OPEN //First level firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear2Stage(); }); thirdActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; innerThirdActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); }); }else if(innerThirdActive === null && innerFourthActive === null && innerSecondActive != null){ console.warn('2lvl meta to go FROM LINK'); //Scroll to the start // const yOffset = -88; // const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; // window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-desktop__title'); if(innerSecondActive){ //CLONE First Meta Title const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-desktop__title--second'); let firstActiveTitleMeta = innerFirstActiveTitle.cloneNode(true); firstActiveTitleMeta.classList.add('shop-catalog-desktop__title--first-meta'); if(intViewportWidth > 1440){ firstActiveTitleMeta.style.marginLeft = '20px'; }else{ firstActiveTitleMeta.style.marginLeft = '0px'; } firstActiveTitleMeta.style.visibility = 'visible'; //CLONE Second Meta Title let secondActiveTitleMeta = innerSecondActiveTitle.cloneNode(true); secondActiveTitleMeta.classList.add('shop-catalog-desktop__title--second-meta'); //Transform to OPEN Phase const innerSecondMetaTitleStaticBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-static--second'); const innerSecondMetaTitleOpenBlock = secondActiveTitleMeta.querySelector('.shop-catalog-desktop__title-open--second'); innerSecondMetaTitleStaticBlock.style.display = 'none'; innerSecondMetaTitleOpenBlock.style.display = 'block'; //Clone Final item ACTIVE const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; // console.warn(secondActiveTitleMeta); // console.warn(shopCatalogInnerThirdActiveTitleMeta); let metaInner = document.createElement('div'); metaInner.classList.add('shop-catalog-desktop__inner--meta'); firstSection.before(metaInner); metaInner.append(firstActiveTitleMeta); metaInner.append(secondActiveTitleMeta); metaInner.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; //Now OPEN //First level firstActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; clearLastOfferData(); //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear1Stage(){ secondSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--second-active'); }); thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear1Stage(); }); secondActiveTitleMeta.addEventListener('click', function(){ firstSection.style.display = 'flex'; innerSecondActive.style.display = 'flex'; //Smooth scroll to the proper position function smoothScrollDelay(){ const yOffset = -88; const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(smoothScrollDelay, 100); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); function innerBlocksActivesClear2Stage(){ thirdSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--third-active'); }); fourthSections.forEach(item => { item.classList.remove('shop-catalog-desktop__inner--fourth-active'); }); } innerBlocksActivesClear2Stage(); }); } }else if(innerThirdActive === null && innerFourthActive === null && innerSecondActive === null){ console.warn('1lvl meta to go FROM LINK'); firstSection.style.display = 'flex'; const yOffset = -70; const y = firstSection.getBoundingClientRect().bottom + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); ShopCatalogDesktopMetaHide(); finalItemActiveClear(); stockHide(); } } } } } setTimeout(shopCatalogDesktopMetaCloserFromLink, 100); //clear final-item active function finalItemActiveClear(){ const finalItemsActive = document.querySelectorAll('.final-item--active'); if(finalItemsActive){ finalItemsActive.forEach(item =>{ item.classList.remove('final-item--active'); }); } } //hide Inner Meta block function ShopCatalogDesktopMetaHide(){ let innerMetaBlock = document.querySelector('.shop-catalog-desktop__inner--meta'); if(innerMetaBlock){ innerMetaBlock.remove(); } } //Final item fetching from server | Desktop function shopCatalogFetchDesktop() { let finalItems = document.querySelectorAll('.final-item'); let offersContainer = document.querySelector('.offersContainer'); let preloaderContainer = document.querySelector('.preloader-container'); const catalogDepBlock = document.querySelector('.catalog__departament'); const firstSection = document.querySelector('.shop-catalog-desktop__inner'); const firstSectionMobile = document.querySelector('.shop-catalog-mobile__inner'); for (let i = 0; i < finalItems.length; i++) { finalItems[i].addEventListener('click', function(e){ e.preventDefault(); fourthBlocksClear(); clearLastOfferData(); const finalItem = this; let finalItemInnerText = finalItem.innerText.toLowerCase(); const firstChar = finalItemInnerText.charAt(0); const finalItemInnerTextCap = finalItemInnerText.replace(firstChar, firstChar.toUpperCase()); document.title = finalItemInnerTextCap; const finalItemParent = finalItem.parentElement; if(finalItemParent.classList.contains('shop-catalog-desktop__item')){ console.warn('Final item in first section!'); // console.warn(finalItemParent); finalItem.classList.add('final-item--active'); const finalItemCode = finalItem.dataset.code; const finalItemUrl = finalItem.getAttribute("href"); let requestUrl = `/catalog/offers/${finalItemCode}`; let finalItemTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(finalItemTextBlock){ finalItemTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } setTimeout(() => { firstSection.style.display = 'flex'; }, 30); fetchingPreloaderErrorRefresh(); preloaderContainer.style.display = 'flex'; preloaderContainer.style.paddingTop = '15px'; //meta mech //shopCatalogDesktopMetaCloser(); function fetchingOffers(){ const xhr = new XMLHttpRequest(); xhr.open("POST", requestUrl, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // const offerContainer = document.querySelector('.offersContainer'); xhr.onreadystatechange = function() { if (this.readyState == 4) { if (this.status == 200) { const response = xhr.response; let responseHtml = document.createElement("div"); responseHtml.innerHTML = response; // shopCatalogMechDesktop(); offersContainer.appendChild(responseHtml); offerCardMobileOpen(); offerCardMobileInfoOpen(); offerCardDesktopOpen(); offerCardDesktopInfoOpen(); offerCardMobileBuyButtonMech(); offerCardDesktopBuyButtonMech(); offerCardDesktopBuyButtonTooltip(); offerCardMobileFastBuy(); offerCardDesktopFastBuy(); offerCardDesktopBuyButtonTooltip(); offerCardDesktopFastBuyTooltipMech(); desktopCardMoreBtn(); offersEpcLinkTip(); offersEpcLinkTipMobile(); offersDesktopNoOfferBorder(); offersCardDesktopFavoriteBtnAdd(); offersCardDesktopFavoriteBtnRemove(); offerCardFavoriteBtnMobileAdd(); offerCardFavoriteBtnMobileRemove(); offersCatalogSortByPriceMechDesktop(); offersCatalogSortByPriceMechMobile(); shopCatalogPager(); shopCatalogFilter(); catalogOffersAskModal(); offersCatalogMoreBtnHelper(); generateNextOfferBtn(); preloaderContainer.style.display = 'none'; offersContainer.style.display = 'block'; const yOffset = -70; const y = offersContainer.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); setTimeout(stockAppearence, 20); }else{ // Обработка ошибки fetchingPreloaderError(); console.error("Ошибка запроса. Статус:", this.status); } } } xhr.send(finalItemUrl); } setTimeout(fetchingOffers, 1000); }else{ // console.warn('Final item on usual place'); // console.warn(finalItemParent); finalItem.classList.add('final-item--active'); const finalItemCode = finalItem.dataset.code; const finalItemUrl = finalItem.getAttribute("href"); let requestUrl = `/catalog/offers/${finalItemCode}`; let finalItemTextBlock = this.querySelector('.shop-catalog-desktop__item-text'); if(finalItemTextBlock){ finalItemTextBlock.classList.add('shop-catalog-desktop__item-text--active'); } fetchingPreloaderErrorRefresh(); preloaderContainer.style.display = 'flex'; preloaderContainer.style.paddingTop = '15px'; //meta mech //shopCatalogDesktopMetaCloser(); //Smooth scroll to the proper position if(catalogDepBlock){ const yOffset = -11; const y = catalogDepBlock.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); } function fetchingOffers(){ const xhr = new XMLHttpRequest(); xhr.open("POST", requestUrl, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // const offerContainer = document.querySelector('.offersContainer'); xhr.onreadystatechange = function() { if(this.readyState == 4){ if(this.status == 200){ const response = xhr.response; let responseHtml = document.createElement("div"); responseHtml.innerHTML = response; // shopCatalogMechDesktop(); offersContainer.appendChild(responseHtml); offerCardMobileOpen(); offerCardMobileInfoOpen(); offerCardDesktopOpen(); offerCardDesktopInfoOpen(); offerCardMobileBuyButtonMech(); offerCardDesktopBuyButtonMech(); offerCardDesktopBuyButtonTooltip(); offerCardMobileFastBuy(); offerCardDesktopFastBuy(); offerCardDesktopBuyButtonTooltip(); offerCardDesktopFastBuyTooltipMech(); desktopCardMoreBtn(); offersEpcLinkTip(); offersEpcLinkTipMobile(); offersCardDesktopFavoriteBtnAdd(); offersCardDesktopFavoriteBtnRemove(); offerCardFavoriteBtnMobileAdd(); offerCardFavoriteBtnMobileRemove(); offersCatalogSortByPriceMechDesktop(); offersCatalogSortByPriceMechMobile(); shopCatalogPager(); shopCatalogFilter(); catalogOffersAskModal(); offersCatalogMoreBtnHelper(); generateNextOfferBtn(); preloaderContainer.style.display = 'none'; offersContainer.style.display = 'block'; setTimeout(stockAppearence, 20); function scrollToOffersDesktop(){ //Smooth scroll to the proper position let intViewportWidth = window.innerWidth; if(intViewportWidth < 1140){ const yOffset = -50; const y = offersContainer.getBoundingClientRect().top + window.pageYOffset + yOffset; console.warn('scroll to offers from fetch desktop ORIENTED TO MOBILE') window.scrollTo({top: y, behavior: 'smooth'}); }else{ const yOffset = -70; const y = offersContainer.getBoundingClientRect().top + window.pageYOffset + yOffset; console.warn('scroll to offers from fetch desktop') window.scrollTo({top: y, behavior: 'smooth'}); } } setTimeout(scrollToOffersDesktop, 100); }else{ // Обработка ошибки fetchingPreloaderError(); console.error("Ошибка запроса. Статус:", this.status); } } } xhr.send(finalItemUrl); } setTimeout(fetchingOffers, 1000); } }); } } // animation: spin 5s infinite; // animation: spin-reverse 5s infinite; function fetchingPreloaderError(){ let preloader = document.querySelector('.preloader-container'); let intViewportWidth = window.innerWidth; if(preloader){ let preloaderContainer = preloader.querySelector('.preloader'); let preloaderText = preloader.querySelector('.preloader__text'); let preloaderGearOne = preloader.querySelector('.one'); let preloaderGearTwo = preloader.querySelector('.two'); let preloaderGearThree = preloader.querySelector('.three'); preloaderContainer.style.filter = 'grayscale(1)'; preloaderGearOne.style.animation = 'spin 0s infinite'; preloaderGearTwo.style.animation = 'spin-reverse 0s infinite'; preloaderGearThree.style.animation = 'spin 0s infinite'; preloaderText.innerText = 'Ошибка! Не удалось загрузить товарные предложения!'; if(intViewportWidth > 1140){ errorBannerDesktop(); }else{ errorBannerMobile(); } } } function fetchingPreloaderErrorRefresh(){ let preloader = document.querySelector('.preloader-container'); if(preloader){ let preloaderContainer = preloader.querySelector('.preloader'); let preloaderText = preloader.querySelector('.preloader__text'); let preloaderGearOne = preloader.querySelector('.one'); let preloaderGearTwo = preloader.querySelector('.two'); let preloaderGearThree = preloader.querySelector('.three'); preloaderContainer.style.filter = 'none'; preloaderGearOne.style.animation = 'spin 5s infinite'; preloaderGearTwo.style.animation = 'spin-reverse 5s infinite'; preloaderGearThree.style.animation = 'spin 5s infinite'; preloaderText.innerText = 'Загружаем товарные предложения!'; } } function stockAppearence(){ const stockFilter = document.querySelector('.stock-filter'); if(stockFilter){ stockFilter.style.visibility = 'visible'; } } function stockHide(){ const stockFilter = document.querySelector('.stock-filter'); if(stockFilter){ stockFilter.style.visibility = 'hidden'; } } function clearLastOfferData() { let offersContainer = document.querySelector('.offersContainer'); let lastFetchedOffer = offersContainer.querySelector('div'); if(lastFetchedOffer === null) { // console.log("offersContainer is empty"); } else { // console.log('offersContainer is NOT empty'); offersContainer.removeChild(lastFetchedOffer); } } //text-block clear functions function modelsClear() { let firstSect = document.querySelectorAll('.shop-catalog-desktop__item'); firstSect.forEach(item => { let modelTextBlock = item.querySelector('.shop-catalog-desktop__item-text'); if(modelTextBlock){ modelTextBlock.classList.remove('shop-catalog-desktop__item-text--active'); } }); } function secondBlocksClear() { let secondSect = document.querySelectorAll('.shop-catalog-desktop__item--second'); secondSect.forEach(item => { let secTextBlock = item.querySelector('.shop-catalog-desktop__item-text'); if(secTextBlock){ secTextBlock.classList.remove('shop-catalog-desktop__item-text--active'); } }); } function thirdBlocksClear() { let thirdSect = document.querySelectorAll('.shop-catalog-desktop__item--third'); thirdSect.forEach(item => { let thirdTextBlock = item.querySelector('.shop-catalog-desktop__item-text'); if(thirdTextBlock){ thirdTextBlock.classList.remove('shop-catalog-desktop__item-text--active'); } }); } function fourthBlocksClear() { let fourthSect = document.querySelectorAll('.shop-catalog-desktop__item--fourth'); fourthSect.forEach(item => { let fourthTextBlock = item.querySelector('.shop-catalog-desktop__item-text'); if(fourthTextBlock){ fourthTextBlock.classList.remove('shop-catalog-desktop__item-text--active'); } }); } function fifthBlocksClear() { let fifthSect = document.querySelectorAll('.shop-catalog-desktop__item--fifth'); fifthSect.forEach(item => { let fifthTextBlock = item.querySelector('.shop-catalog-desktop__item-text'); if(fifthTextBlock){ fifthTextBlock.classList.remove('shop-catalog-desktop__item-text--active'); } }); } function sixthBlocksClear() { let sixthSect = document.querySelectorAll('.shop-catalog-desktop__item--sixth'); sixthSect.forEach(item => { let sixthTextBlock = item.querySelector('.shop-catalog-desktop__item-text'); if(sixthTextBlock){ sixthTextBlock.classList.remove('shop-catalog-desktop__item-text--active'); } }); } function seventhBlocksClear() { let seventhSect = document.querySelectorAll('.shop-catalog-desktop__item--seventh'); seventhSect.forEach(item => { let seventhTextBlock = item.querySelector('.shop-catalog-desktop__item-text'); if(seventhTextBlock){ seventhTextBlock.classList.remove('shop-catalog-desktop__item-text--active'); } }); } //mobile functions function shopCatalogMechMobile(){ let modelsMobile = document.querySelectorAll('.shop-catalog-mobile-item'); let secondSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--second'); let secondSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--second'); let thirdSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--third'); let thirdSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--third'); let fourthSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--fourth'); let fourthSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--fourth'); let fifthSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--fifth'); let fifthSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--fifth'); let sixthSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--sixth'); let sixthSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--sixth'); let seventhSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--seventh'); let seventhSectionItemsMobile = document.querySelectorAll('.shop-catalog-mobile-item--seventh'); // click on each model mobile 1lvl for (let i = 0; i < modelsMobile.length; i++) { modelsMobile[i].addEventListener('click', function (e) { e.preventDefault(); seventhBlocksMobileClear(); sixthBlocksMobileClear(); fifthBlocksMobileClear(); fourthBlocksMobileClear(); thirdBlocksMobileClear(); secondBlocksMobileClear(); modelsMobileClear(); clearLastOfferData(); stockHide(); function clearOpenedSections1lvl(){ //clear opened second sections secondSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened third sections thirdSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened fourth sections fourthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened fifth sections fifthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened sixth sections sixthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened seventh sections seventhSectionsMobile.forEach(item => { item.style.display = 'none'; }) } clearOpenedSections1lvl(); let modelMobile = this.querySelector('a'); let modelMobileText = this.querySelector('.shop-catalog-mobile-item__text'); modelMobileText.classList.add('shop-catalog-mobile-item__text--active'); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear1StageMobile(); if(modelMobile.classList.contains('final-item-mobile')){ console.log('first is final - only load offers') const mobileCatalogInner = document.querySelector('.shop-catalog-mobile__inner'); //Smooth scroll to the proper position const yOffset = -10; const y = mobileCatalogInner.getBoundingClientRect().bottom + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); innerBlocksActivesClear1StageMobile(); shopCatalogMobileMetaHide(); shopCatalogMobileMetaCloser(); mobileCatalogInner.style.display = 'block'; }else{ secondSectionsMobile.forEach(item => { if(item.dataset.code == modelMobile.dataset.code) { let currentSecondSectionMobile = item; currentSecondSectionMobile.style.display = 'block'; currentSecondSectionMobile.classList.add('shop-catalog-mobile__inner--second-active'); currentSecondSectionMobile.scrollIntoView({behavior: "smooth"}); } }) } }) } // click on each item in 2lvl for (let i = 0; i < secondSectionItemsMobile.length; i++){ secondSectionItemsMobile[i].addEventListener('click', function(e){ e.preventDefault(); function clearOpenedSections1lvl(){ //clear opened third sections thirdSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened fourth sections fourthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened fifth sections fifthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened sixth sections sixthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened seventh sections seventhSectionsMobile.forEach(item => { item.style.display = 'none'; }) } clearOpenedSections1lvl(); seventhBlocksMobileClear(); sixthBlocksMobileClear(); fifthBlocksMobileClear(); fourthBlocksMobileClear(); thirdBlocksMobileClear(); secondBlocksMobileClear(); clearLastOfferData(); stockHide(); let currentSecondItemMobile = this.querySelector('a'); let currentSecondItemMobileText = this.querySelector('.shop-catalog-mobile-item__text'); currentSecondItemMobileText.classList.add('shop-catalog-mobile-item__text--active'); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear2StageMobile(); if(currentSecondItemMobile.classList.contains('final-item-mobile')){ // console.log('this is final - only load offers') shopCatalogMobileMetaHide(); shopCatalogMobileMetaCloser(); }else{ thirdSectionsMobile.forEach(item => { if(item.dataset.code == currentSecondItemMobile.dataset.code){ let currentThirdSectionMobile = item; currentThirdSectionMobile.style.display = 'block'; currentThirdSectionMobile.classList.add('shop-catalog-mobile__inner--third-active'); currentThirdSectionMobile.scrollIntoView({behavior: "smooth"}); } }) } }) } // click on each item in 3lvl for (let i = 0; i < thirdSectionItemsMobile.length; i++){ thirdSectionItemsMobile[i].addEventListener('click', function(e){ e.preventDefault(); function clearOpenedSections3lvl(){ //clear opened fourth sections fourthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened fifth sections fifthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened sixth sections sixthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened seventh sections seventhSectionsMobile.forEach(item => { item.style.display = 'none'; }) } clearOpenedSections3lvl(); seventhBlocksMobileClear(); sixthBlocksMobileClear(); fifthBlocksMobileClear(); fourthBlocksMobileClear(); thirdBlocksMobileClear(); clearLastOfferData(); stockHide(); let currentThirdItemMobile = this.querySelector('a'); let currentThirdItemMobileText = this.querySelector('.shop-catalog-mobile-item__text'); currentThirdItemMobileText.classList.add('shop-catalog-mobile-item__text--active'); function innerBlocksActivesClear3StageMobile(){ fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear3StageMobile(); // currentThirdItemMobile.classList.add('shop-catalog-mobile__inner--third-active'); if(currentThirdItemMobile.classList.contains('final-item-mobile')){ // console.log('this is final - only load offers') shopCatalogMobileMetaHide(); shopCatalogMobileMetaCloser(); }else{ fourthSectionsMobile.forEach(item => { if(item.dataset.code == currentThirdItemMobile.dataset.code){ let currentFourthSectionMobile = item; currentFourthSectionMobile.style.display = 'block'; currentFourthSectionMobile.classList.add('shop-catalog-mobile__inner--fourth-active'); currentFourthSectionMobile.scrollIntoView({behavior: "smooth"}); } }) } }) } // click on each item in 4lvl for (let i = 0; i < fourthSectionItemsMobile.length; i++){ fourthSectionItemsMobile[i].addEventListener('click', function(e){ e.preventDefault(); seventhBlocksMobileClear(); sixthBlocksMobileClear(); fifthBlocksMobileClear(); fourthBlocksMobileClear(); clearLastOfferData(); stockHide(); function clearOpenedSections4lvl(){ //clear opened fifth sections fifthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened sixth sections sixthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened seventh sections seventhSectionsMobile.forEach(item => { item.style.display = 'none'; }) } clearOpenedSections4lvl(); let currentFourthItemMobile = this.querySelector('a'); let currentFourthItemMobileText = this.querySelector('.shop-catalog-mobile-item__text'); currentFourthItemMobileText.classList.add('shop-catalog-mobile-item__text--active'); function innerBlocksActivesClear4StageMobile(){ fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear4StageMobile(); if(currentFourthItemMobile.classList.contains('final-item-mobile')){ // console.log('this is final - only load offers') shopCatalogMobileMetaHide(); shopCatalogMobileMetaCloser(); }else{ fifthSectionsMobile.forEach(item => { if(item.dataset.code == currentFourthItemMobile.dataset.code){ let currentFifthSectionMobile = item; currentFifthSectionMobile.style.display = 'block'; currentFifthSectionMobile.classList.add('shop-catalog-mobile__inner--fifth-active'); currentFifthSectionMobile.scrollIntoView({behavior: "smooth"}); } }) } }) } // click on each item in 5lvl for (let i = 0; i < fifthSectionItemsMobile.length; i++){ fifthSectionItemsMobile[i].addEventListener('click', function(e){ e.preventDefault(); seventhBlocksMobileClear(); sixthBlocksMobileClear(); fifthBlocksMobileClear(); clearLastOfferData(); stockHide(); function clearOpenedSections5lvl(){ //clear opened sixth sections sixthSectionsMobile.forEach(item => { item.style.display = 'none'; }) //clear opened seventh sections seventhSectionsMobile.forEach(item => { item.style.display = 'none'; }) } clearOpenedSections5lvl(); let currentFifthItemMobile = this.querySelector('a'); let currentFifthItemMobileText = this.querySelector('.shop-catalog-mobile-item__text'); currentFifthItemMobileText.classList.add('shop-catalog-mobile-item__text--active'); function innerBlocksActivesClear5StageMobile(){ sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear5StageMobile(); if(currentFifthItemMobile.classList.contains('final-item-mobile')){ // console.log('this is final - only load offers') shopCatalogMobileMetaHide(); shopCatalogMobileMetaCloser(); }else{ sixthSectionsMobile.forEach(item => { if(item.dataset.code == currentFifthItemMobile.dataset.code){ let currentSixthSectionMobile = item; currentSixthSectionMobile.style.display = 'block'; currentSixthSectionMobile.classList.add('shop-catalog-mobile__inner--sixth-active'); currentSixthSectionMobile.scrollIntoView({behavior: "smooth"}); } }) } }) } // click on each item in 6lvl for (let i = 0; i < sixthSectionItemsMobile.length; i++){ sixthSectionItemsMobile[i].addEventListener('click', function(e){ e.preventDefault(); seventhBlocksMobileClear(); sixthBlocksMobileClear(); clearLastOfferData(); stockHide(); function clearOpenedSections5lvl(){ //clear opened seventh sections seventhSectionsMobile.forEach(item => { item.style.display = 'none'; }) } clearOpenedSections5lvl(); let currentSixthItemMobile = this.querySelector('a'); let currentSixthItemMobileText = this.querySelector('.shop-catalog-mobile-item__text'); currentSixthItemMobileText.classList.add('shop-catalog-mobile-item__text--active'); function innerBlocksActivesClear6StageMobile(){ seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear6StageMobile(); if(currentSixthItemMobile.classList.contains('final-item-mobile')){ // console.log('this is final - only load offers') shopCatalogMobileMetaHide(); shopCatalogMobileMetaCloser(); }else{ seventhSectionsMobile.forEach(item => { if(item.dataset.code == currentSixthItemMobile.dataset.code){ let currentSeventhSectionMobile = item; currentSeventhSectionMobile.style.display = 'block'; currentSeventhSectionMobile.classList.add('shop-catalog-mobile__inner--seventh-active'); currentSeventhSectionMobile.scrollIntoView({behavior: "smooth"}); } }) } }) } // click on each item in 7lvl for (let i = 0; i < seventhSectionItemsMobile.length; i++){ seventhSectionItemsMobile[i].addEventListener('click', function(e){ e.preventDefault(); console.warn('7 lvl is final'); seventhBlocksMobileClear(); clearLastOfferData(); stockHide(); let currentSeventhItemMobile = this.querySelector('a'); let currentSeventhItemMobileText = this.querySelector('.shop-catalog-mobile-item__text'); if(currentSeventhItemMobileText){ currentSeventhItemMobileText.classList.add('shop-catalog-mobile-item__text--active'); } shopCatalogMobileMetaHide(); shopCatalogMobileMetaCloser(); }) } } //meta for mobile function shopCatalogMobileMetaCloser(){ let firstSection = document.querySelector('.shop-catalog-mobile__inner'); const innerSecondActive = document.querySelector('.shop-catalog-mobile__inner--second-active'); const innerThirdActive = document.querySelector('.shop-catalog-mobile__inner--third-active'); const innerFourthActive = document.querySelector('.shop-catalog-mobile__inner--fourth-active'); const innerFifthActive = document.querySelector('.shop-catalog-mobile__inner--fifth-active'); const innerSixthActive = document.querySelector('.shop-catalog-mobile__inner--sixth-active'); const innerSeventhActive = document.querySelector('.shop-catalog-mobile__inner--seventh-active'); const finalItemActive = document.querySelector('.final-item-mobile--active'); let secondSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--second'); let thirdSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--third'); let fourthSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--fourth'); let fifthSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--fifth'); let sixthSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--sixth'); let seventhSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--seventh'); if(innerSeventhActive){ // console.warn('7 lvl mobile meta go'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-mobile__title'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-mobile__title'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-mobile__title'); const innerSixthActiveTitle = innerSixthActive.querySelector('.shop-catalog-mobile__title'); const innerSeventhActiveTitle = innerSeventhActive.querySelector('.shop-catalog-mobile__title'); //Create first title meta let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Create third title meta let thirdMetaItem = document.createElement('div'); thirdMetaItem.classList.add('shop-catalog-mobile__meta-item'); thirdMetaItem.innerText = innerThirdActiveTitle.innerText; // Clone Fourth Meta Title let fourthMetaItem = document.createElement('div'); fourthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fourthMetaItem.innerText = innerFourthActiveTitle.innerText; // Clone Fifth Meta Title let fifthMetaItem = document.createElement('div'); fifthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fifthMetaItem.innerText = innerFifthActiveTitle.innerText; // Clone Sixth Meta Title let sixthMetaItem = document.createElement('div'); sixthMetaItem.classList.add('shop-catalog-mobile__meta-item'); sixthMetaItem.innerText = innerSixthActiveTitle.innerText; // Clone Seventh Meta Title let seventhMetaItem = document.createElement('div'); seventhMetaItem.classList.add('shop-catalog-mobile__meta-item'); seventhMetaItem.innerText = innerSeventhActiveTitle.innerText; //Clone finalItem mobile const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(thirdMetaItem); metaInnerMobile.append(fourthMetaItem); metaInnerMobile.append(fifthMetaItem); metaInnerMobile.append(sixthMetaItem); metaInnerMobile.append(seventhMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; innerSixthActive.style.display = 'none'; innerSeventhActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear2StageMobile(); }); thirdMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear3StageMobile(){ fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear3StageMobile(); }); fourthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear4StageMobile(){ fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear4StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); fifthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear5StageMobile(){ sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear5StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); sixthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; innerSixthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerSixthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear6StageMobile(){ seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear6StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); seventhMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; innerSixthActive.style.display = 'block'; innerSeventhActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerSeventhActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); }else if(innerSixthActive){ // console.warn('6 lvl mobile meta go'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-mobile__title'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-mobile__title'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-mobile__title'); const innerSixthActiveTitle = innerSixthActive.querySelector('.shop-catalog-mobile__title'); //Create first title meta let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Create third title meta let thirdMetaItem = document.createElement('div'); thirdMetaItem.classList.add('shop-catalog-mobile__meta-item'); thirdMetaItem.innerText = innerThirdActiveTitle.innerText; // Clone Fourth Meta Title let fourthMetaItem = document.createElement('div'); fourthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fourthMetaItem.innerText = innerFourthActiveTitle.innerText; // Clone Fifth Meta Title let fifthMetaItem = document.createElement('div'); fifthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fifthMetaItem.innerText = innerFifthActiveTitle.innerText; // Clone Sixth Meta Title let sixthMetaItem = document.createElement('div'); sixthMetaItem.classList.add('shop-catalog-mobile__meta-item'); sixthMetaItem.innerText = innerSixthActiveTitle.innerText; //Clone finalItem mobile const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(thirdMetaItem); metaInnerMobile.append(fourthMetaItem); metaInnerMobile.append(fifthMetaItem); metaInnerMobile.append(sixthMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; innerSixthActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); } innerBlocksActivesClear2StageMobile(); }); thirdMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear3StageMobile(){ fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); } innerBlocksActivesClear3StageMobile(); }); fourthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear4StageMobile(){ fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); } innerBlocksActivesClear4StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); fifthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear5StageMobile(){ sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); } innerBlocksActivesClear5StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); sixthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; innerSixthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerSixthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); }else if(innerFifthActive){ // console.warn('5 lvl mobile meta go'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-mobile__title'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-mobile__title'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-mobile__title'); //Create first title meta let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Create third title meta let thirdMetaItem = document.createElement('div'); thirdMetaItem.classList.add('shop-catalog-mobile__meta-item'); thirdMetaItem.innerText = innerThirdActiveTitle.innerText; // Clone Fourth Meta Title let fourthMetaItem = document.createElement('div'); fourthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fourthMetaItem.innerText = innerFourthActiveTitle.innerText; // Clone Fifth Meta Title let fifthMetaItem = document.createElement('div'); fifthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fifthMetaItem.innerText = innerFifthActiveTitle.innerText; //Clone finalItem mobile const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(thirdMetaItem); metaInnerMobile.append(fourthMetaItem); metaInnerMobile.append(fifthMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); } innerBlocksActivesClear2StageMobile(); }); thirdMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear3StageMobile(){ fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); } innerBlocksActivesClear3StageMobile(); }); fourthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear4StageMobile(){ fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); } innerBlocksActivesClear4StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); fifthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); }else if(innerFourthActive){ // console.warn('4 lvl mobile meta go'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-mobile__title'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-mobile__title'); //Create first title meta let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Create third title meta let thirdMetaItem = document.createElement('div'); thirdMetaItem.classList.add('shop-catalog-mobile__meta-item'); thirdMetaItem.innerText = innerThirdActiveTitle.innerText; // Clone Fourth Meta Title let fourthMetaItem = document.createElement('div'); fourthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fourthMetaItem.innerText = innerFourthActiveTitle.innerText; //Clone finalItem mobile const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(thirdMetaItem); metaInnerMobile.append(fourthMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear2StageMobile(); }); thirdMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear3StageMobile(){ fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear3StageMobile(); }); fourthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); }else if(innerThirdActive){ // console.warn('3 lvl mobile meta go'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-mobile__title'); let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Create third title meta let thirdMetaItem = document.createElement('div'); thirdMetaItem.classList.add('shop-catalog-mobile__meta-item'); thirdMetaItem.innerText = innerThirdActiveTitle.innerText; //Clone finalItem mobile const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(thirdMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear2StageMobile(); }); thirdMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear3StageMobile(){ fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear3StageMobile(); }); }else if(innerThirdActive === null && innerFourthActive === null && innerSecondActive != null){ // console.warn('2 lvl mobile meta go'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); //Create first title meta let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Clone finalItem mobile const finalItemParent = finalItemActive.parentElement; const finalItemActiveMeta = finalItemParent.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear2StageMobile(); }); }else if(innerThirdActive === null && innerFourthActive === null && innerSecondActive === null){ // console.warn('1 lvl mobile | no meta'); firstSection.style.display = 'block'; const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); } } //meta mobile from link function shopCatalogMobileMetaCloserFromLink(){ let firstSection = document.querySelector('.shop-catalog-mobile__inner'); let intViewportWidth = window.innerWidth; if(firstSection){ if(intViewportWidth < 1140){ const innerSeconds = document.querySelectorAll('.shop-catalog-mobile__inner--second'); const innerThirds = document.querySelectorAll('.shop-catalog-mobile__inner--third'); const innerFourth = document.querySelectorAll('.shop-catalog-mobile__inner--fourth'); const innerFifth = document.querySelectorAll('.shop-catalog-mobile__inner--fifth'); const innerSixth = document.querySelectorAll('.shop-catalog-mobile__inner--sixth'); const innerSeventh = document.querySelectorAll('.shop-catalog-mobile__inner--seventh'); let secondSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--second'); let thirdSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--third'); let fourthSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--fourth'); let fifthSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--fifth'); let sixthSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--sixth'); let seventhSectionsMobile = document.querySelectorAll('.shop-catalog-mobile__inner--seventh'); const shopCatalogParentMobile = document.querySelector('.catalog__departament'); const finalItemActive = document.querySelector('.final-item-mobile .shop-catalog-mobile-item__text--active'); if(finalItemActive){ //Smooth scroll to the proper position const yOffset = -10; const y = shopCatalogParentMobile.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); //find active/visible seventh block here innerSeventh.forEach(item => { if(window.getComputedStyle(item).display == 'block'){ item.classList.add('shop-catalog-mobile__inner--seventh-active'); } }); //find active/visible sixth block here innerSixth.forEach(item => { if(window.getComputedStyle(item).display == 'block'){ item.classList.add('shop-catalog-mobile__inner--sixth-active'); } }); //find active/visible fifth block here innerFifth.forEach(item => { if(window.getComputedStyle(item).display == 'block'){ item.classList.add('shop-catalog-mobile__inner--fifth-active'); } }); //find active/visible fourth block here innerFourth.forEach(item => { if(window.getComputedStyle(item).display == 'block'){ item.classList.add('shop-catalog-mobile__inner--fourth-active'); } }); //find active/visible thirds block here innerThirds.forEach(item => { if(window.getComputedStyle(item).display == 'block'){ item.classList.add('shop-catalog-mobile__inner--third-active'); } }); //find active/visible second block here innerSeconds.forEach(item => { if(window.getComputedStyle(item).display == 'block'){ item.classList.add('shop-catalog-mobile__inner--second-active'); } }); const innerSecondActive = document.querySelector('.shop-catalog-mobile__inner--second-active'); const innerThirdActive = document.querySelector('.shop-catalog-mobile__inner--third-active'); const innerFourthActive = document.querySelector('.shop-catalog-mobile__inner--fourth-active'); const innerFifthActive = document.querySelector('.shop-catalog-mobile__inner--fifth-active'); const innerSixthActive = document.querySelector('.shop-catalog-mobile__inner--sixth-active'); const innerSeventhActive = document.querySelector('.shop-catalog-mobile__inner--seventh-active'); if(innerSeventhActive){ console.warn('7 lvl mobile meta go FROM LINK'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-mobile__title'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-mobile__title'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-mobile__title'); const innerSixthActiveTitle = innerSixthActive.querySelector('.shop-catalog-mobile__title'); const innerSeventhActiveTitle = innerSeventhActive.querySelector('.shop-catalog-mobile__title'); //Create first title meta let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Create third title meta let thirdMetaItem = document.createElement('div'); thirdMetaItem.classList.add('shop-catalog-mobile__meta-item'); thirdMetaItem.innerText = innerThirdActiveTitle.innerText; // Clone Fourth Meta Title let fourthMetaItem = document.createElement('div'); fourthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fourthMetaItem.innerText = innerFourthActiveTitle.innerText; // Clone Fifth Meta Title let fifthMetaItem = document.createElement('div'); fifthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fifthMetaItem.innerText = innerFifthActiveTitle.innerText; // Clone Sixth Meta Title let sixthMetaItem = document.createElement('div'); sixthMetaItem.classList.add('shop-catalog-mobile__meta-item'); sixthMetaItem.innerText = innerSixthActiveTitle.innerText; // Clone Seventh Meta Title let seventhMetaItem = document.createElement('div'); seventhMetaItem.classList.add('shop-catalog-mobile__meta-item'); seventhMetaItem.innerText = innerSeventhActiveTitle.innerText; //Clone finalItem mobile const finalItemParentALink = finalItemActive.parentNode; const finalItemParentAfterALink = finalItemParentALink.parentNode; const finalItemActiveMeta = finalItemParentAfterALink.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(thirdMetaItem); metaInnerMobile.append(fourthMetaItem); metaInnerMobile.append(fifthMetaItem); metaInnerMobile.append(sixthMetaItem); metaInnerMobile.append(seventhMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; innerSixthActive.style.display = 'none'; innerSeventhActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear2StageMobile(); }); thirdMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear3StageMobile(){ fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear3StageMobile(); }); fourthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear4StageMobile(){ fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear4StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); fifthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear5StageMobile(){ sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear5StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); sixthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; innerSixthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerSixthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear6StageMobile(){ seventhSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--seventh-active'); }); } innerBlocksActivesClear6StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); seventhMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; innerSixthActive.style.display = 'block'; innerSeventhActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerSeventhActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); }else if(innerSixthActive){ console.warn('6 lvl mobile meta go FROM LINK'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-mobile__title'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-mobile__title'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-mobile__title'); const innerSixthActiveTitle = innerSixthActive.querySelector('.shop-catalog-mobile__title'); //Create first title meta let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Create third title meta let thirdMetaItem = document.createElement('div'); thirdMetaItem.classList.add('shop-catalog-mobile__meta-item'); thirdMetaItem.innerText = innerThirdActiveTitle.innerText; // Clone Fourth Meta Title let fourthMetaItem = document.createElement('div'); fourthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fourthMetaItem.innerText = innerFourthActiveTitle.innerText; // Clone Fifth Meta Title let fifthMetaItem = document.createElement('div'); fifthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fifthMetaItem.innerText = innerFifthActiveTitle.innerText; // Clone Sixth Meta Title let sixthMetaItem = document.createElement('div'); sixthMetaItem.classList.add('shop-catalog-mobile__meta-item'); sixthMetaItem.innerText = innerSixthActiveTitle.innerText; //Clone finalItem mobile const finalItemParentALink = finalItemActive.parentNode; const finalItemParentAfterALink = finalItemParentALink.parentNode; const finalItemActiveMeta = finalItemParentAfterALink.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(thirdMetaItem); metaInnerMobile.append(fourthMetaItem); metaInnerMobile.append(fifthMetaItem); metaInnerMobile.append(sixthMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; innerSixthActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); } innerBlocksActivesClear2StageMobile(); }); thirdMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear3StageMobile(){ fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); } innerBlocksActivesClear3StageMobile(); }); fourthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear4StageMobile(){ fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); } innerBlocksActivesClear4StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); fifthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear5StageMobile(){ sixthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--sixth-active'); }); } innerBlocksActivesClear5StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); sixthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; innerSixthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerSixthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); }else if(innerFifthActive){ console.warn('5 lvl mobile meta go FROM LINK'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-mobile__title'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-mobile__title'); const innerFifthActiveTitle = innerFifthActive.querySelector('.shop-catalog-mobile__title'); //Create first title meta let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Create third title meta let thirdMetaItem = document.createElement('div'); thirdMetaItem.classList.add('shop-catalog-mobile__meta-item'); thirdMetaItem.innerText = innerThirdActiveTitle.innerText; // Clone Fourth Meta Title let fourthMetaItem = document.createElement('div'); fourthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fourthMetaItem.innerText = innerFourthActiveTitle.innerText; // Clone Fifth Meta Title let fifthMetaItem = document.createElement('div'); fifthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fifthMetaItem.innerText = innerFifthActiveTitle.innerText; //Clone finalItem mobile const finalItemParentALink = finalItemActive.parentNode; const finalItemParentAfterALink = finalItemParentALink.parentNode; const finalItemActiveMeta = finalItemParentAfterALink.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(thirdMetaItem); metaInnerMobile.append(fourthMetaItem); metaInnerMobile.append(fifthMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; innerFifthActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); } innerBlocksActivesClear2StageMobile(); }); thirdMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear3StageMobile(){ fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); } innerBlocksActivesClear3StageMobile(); }); fourthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); function innerBlocksActivesClear4StageMobile(){ fifthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fifth-active'); }); } innerBlocksActivesClear4StageMobile(); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); fifthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; innerFifthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFifthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); }else if(innerFourthActive){ console.warn('4 lvl mobile meta go FROM LINK'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-mobile__title'); const innerFourthActiveTitle = innerFourthActive.querySelector('.shop-catalog-mobile__title'); //Create first title meta let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Create third title meta let thirdMetaItem = document.createElement('div'); thirdMetaItem.classList.add('shop-catalog-mobile__meta-item'); thirdMetaItem.innerText = innerThirdActiveTitle.innerText; // Clone Fourth Meta Title let fourthMetaItem = document.createElement('div'); fourthMetaItem.classList.add('shop-catalog-mobile__meta-item'); fourthMetaItem.innerText = innerFourthActiveTitle.innerText; //Clone finalItem mobile const finalItemParentALink = finalItemActive.parentNode; const finalItemParentAfterALink = finalItemParentALink.parentNode; const finalItemActiveMeta = finalItemParentAfterALink.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(thirdMetaItem); metaInnerMobile.append(fourthMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; innerFourthActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear2StageMobile(); }); thirdMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear3StageMobile(){ fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear3StageMobile(); }); fourthMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; innerFourthActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerFourthActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); }); }else if(innerThirdActive){ console.warn('3 lvl mobile meta go FROM LINK'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); const innerThirdActiveTitle = innerThirdActive.querySelector('.shop-catalog-mobile__title'); let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Create third title meta let thirdMetaItem = document.createElement('div'); thirdMetaItem.classList.add('shop-catalog-mobile__meta-item'); thirdMetaItem.innerText = innerThirdActiveTitle.innerText; // //Clone finalItem mobile // const finalItemParent = finalItemActive.parentElement; // const finalItemActiveMeta = finalItemParent.cloneNode(true); //Clone finalItem mobile const finalItemParentALink = finalItemActive.parentNode; const finalItemParentAfterALink = finalItemParentALink.parentNode; const finalItemActiveMeta = finalItemParentAfterALink.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(thirdMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; innerThirdActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear2StageMobile(); }); thirdMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; innerThirdActive.style.display = 'block'; clearLastOfferData(); function scrollToThirdTitleMobile(){ const y = innerThirdActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToThirdTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear3StageMobile(){ fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear3StageMobile(); }); }else if(innerThirdActive === null && innerFourthActive === null && innerSecondActive != null){ console.warn('2 lvl mobile meta go FROM LINK'); //Scroll to the proper position const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); const innerFirstActiveTitle = firstSection.querySelector('.shop-catalog-mobile__title'); const innerSecondActiveTitle = innerSecondActive.querySelector('.shop-catalog-mobile__title'); //Create first title meta let firstMetaItem = document.createElement('div'); firstMetaItem.classList.add('shop-catalog-mobile__meta-item'); firstMetaItem.innerText = innerFirstActiveTitle.innerText; //Create second title meta let secondMetaItem = document.createElement('div'); secondMetaItem.classList.add('shop-catalog-mobile__meta-item'); secondMetaItem.innerText = innerSecondActiveTitle.innerText; //Clone finalItem mobile const finalItemParentALink = finalItemActive.parentNode; const finalItemParentAfterALink = finalItemParentALink.parentNode; const finalItemActiveMeta = finalItemParentAfterALink.cloneNode(true); finalItemActiveMeta.classList.add('final-item--active-meta'); finalItemActiveMeta.style.pointerEvents = 'none'; finalItemActiveMeta.style.display = 'block'; //generate and past meta block let metaInnerMobile = document.createElement('div'); metaInnerMobile.classList.add('shop-catalog-mobile__meta-inner'); firstSection.before(metaInnerMobile); metaInnerMobile.append(firstMetaItem); metaInnerMobile.append(secondMetaItem); metaInnerMobile.append(finalItemActiveMeta); firstSection.style.display = 'none'; innerSecondActive.style.display = 'none'; firstMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; clearLastOfferData(); function scrollToFirstTitleMobile(){ const y = firstSection.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToFirstTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear1StageMobile(){ secondSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--second-active'); }); thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear1StageMobile(); }); secondMetaItem.addEventListener('click', function(){ firstSection.style.display = 'block'; innerSecondActive.style.display = 'block'; clearLastOfferData(); function scrollToSecondTitleMobile(){ const y = innerSecondActive.getBoundingClientRect().top + window.pageYOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToSecondTitleMobile, 100); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); function innerBlocksActivesClear2StageMobile(){ thirdSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--third-active'); }); fourthSectionsMobile.forEach(item => { item.classList.remove('shop-catalog-mobile__inner--fourth-active'); }); } innerBlocksActivesClear2StageMobile(); }); }else if(innerThirdActive === null && innerFourthActive === null && innerSecondActive === null){ console.warn('1 lvl mobile | no meta FROM LINK'); firstSection.style.display = 'block'; const yOffset = -10; const y = firstSection.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'instant'}); shopCatalogMobileMetaHide(); finalItemActiveClearMobile(); stockHide(); } } } } } // shopCatalogMobileMetaCloserFromLink(); setTimeout(shopCatalogMobileMetaCloserFromLink ,100); //clear final-item on mobile function finalItemActiveClearMobile(){ const finalItemsActiveMobile = document.querySelectorAll('.final-item-mobile--active'); if(finalItemsActiveMobile === null){ }else{ finalItemsActiveMobile.forEach(item =>{ item.classList.remove('final-item-mobile--active'); }); } } //hide Inner Meta block on nMobile function shopCatalogMobileMetaHide(){ let innerMetaBlockMobile = document.querySelector('.shop-catalog-mobile__meta-inner'); if(innerMetaBlockMobile){ innerMetaBlockMobile.remove(); } } //Final item fetching from server | Mobile function shopCatalogFetchMobile() { let finalItemsMobile = document.querySelectorAll('.final-item-mobile'); let offersContainer = document.querySelector('.offersContainer'); let preloaderContainer = document.querySelector('.preloader-container'); const mobileShopCatalogParent = document.querySelector('.shop-catalog-mobile'); for (let i = 0; i < finalItemsMobile.length; i++) { finalItemsMobile[i].addEventListener('click', function(e){ e.preventDefault(); clearLastOfferData(); const finalItemMobile = this; let finalItemInnerText = finalItemMobile.innerText.toLowerCase(); const firstChar = finalItemInnerText.charAt(0); const finalItemInnerTextCap = finalItemInnerText.replace(firstChar, firstChar.toUpperCase()); document.title = finalItemInnerTextCap; const finalItemMobileParent = finalItemMobile.parentElement; const finalItemMobileCode = finalItemMobile.dataset.code; finalItemMobile.classList.add('final-item-mobile--active'); const finalItemUrlMobile = finalItemMobile.getAttribute("href"); let requestUrlMobile = `/catalog/offers/${finalItemMobileCode}`; // console.log(requestUrl); fetchingPreloaderErrorRefresh(); preloaderContainer.style.display = 'flex'; function fetchingOffersMobile() { const xhr = new XMLHttpRequest(); xhr.open("POST", requestUrlMobile, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (this.readyState == 4) { if (this.status == 200){ const response = xhr.response; let responseHtml = document.createElement("div"); responseHtml.innerHTML = response; offersContainer.appendChild(responseHtml); offerCardMobileOpen(); offerCardMobileInfoOpen(); offerCardDesktopOpen(); offerCardDesktopInfoOpen(); offerCardMobileBuyButtonMech(); offerCardDesktopBuyButtonMech(); offerCardMobileFastBuy(); offerCardDesktopFastBuy(); desktopCardMoreBtn(); offersEpcLinkTip(); offersEpcLinkTipMobile(); offersCardDesktopFavoriteBtnAdd(); offersCardDesktopFavoriteBtnRemove(); offerCardFavoriteBtnMobileAdd(); offerCardFavoriteBtnMobileRemove(); offersCatalogSortByPriceMechDesktop(); offersCatalogSortByPriceMechMobile(); shopCatalogPager(); shopCatalogFilter(); catalogOffersAskModal(); offersCatalogMoreBtnHelper(); generateNextOfferBtn(); preloaderContainer.style.display = 'none'; offersContainer.style.display = 'block'; function scrollToOffersMobile(){ console.warn('delayed scroll mobile fetch') const yOffset = 1; const y = mobileShopCatalogParent.getBoundingClientRect().bottom + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } setTimeout(scrollToOffersMobile, 100); setTimeout(stockAppearence, 20); }else{ // Обработка ошибки fetchingPreloaderError(); console.error("Ошибка запроса. Статус:", this.status); } } } xhr.send(finalItemUrlMobile); } setTimeout(fetchingOffersMobile, 1000); }) } } //text-block clear functions function modelsMobileClear() { let firstSectionMobile = document.querySelector('.shop-catalog-mobile__inner'); let firstSectionMobileItems = firstSectionMobile.querySelectorAll('.shop-catalog-mobile-item'); firstSectionMobileItems.forEach(item => { let modelTextBlock = item.querySelector('.shop-catalog-mobile-item__text'); if(modelTextBlock){ modelTextBlock.classList.remove('shop-catalog-mobile-item__text--active'); } }) } function secondBlocksMobileClear() { let secondSectionsMobileItems = document.querySelectorAll('.shop-catalog-mobile-item--second'); secondSectionsMobileItems.forEach(item => { let secTextBlockMobile = item.querySelector('.shop-catalog-mobile-item__text'); if(secTextBlockMobile){ secTextBlockMobile.classList.remove('shop-catalog-mobile-item__text--active'); } }) } function thirdBlocksMobileClear() { let thirdSectionsMobileItems = document.querySelectorAll('.shop-catalog-mobile-item--third'); thirdSectionsMobileItems.forEach(item => { let thirdTextBlockMobile = item.querySelector('.shop-catalog-mobile-item__text'); if(thirdTextBlockMobile){ thirdTextBlockMobile.classList.remove('shop-catalog-mobile-item__text--active'); } }) } function fourthBlocksMobileClear() { let fourthSectionsMobileItems = document.querySelectorAll('.shop-catalog-mobile-item--fourth'); fourthSectionsMobileItems.forEach(item => { let fourthTextBlockMobile = item.querySelector('.shop-catalog-mobile-item__text'); if(fourthTextBlockMobile){ fourthTextBlockMobile.classList.remove('shop-catalog-mobile-item__text--active'); } }) } function fifthBlocksMobileClear() { let fifthSectionsMobileItems = document.querySelectorAll('.shop-catalog-mobile-item--fifth'); fifthSectionsMobileItems.forEach(item => { let fifthTextBlockMobile = item.querySelector('.shop-catalog-mobile-item__text'); if(fifthTextBlockMobile){ fifthTextBlockMobile.classList.remove('shop-catalog-mobile-item__text--active'); } }) } function sixthBlocksMobileClear() { let sixthSectionsMobileItems = document.querySelectorAll('.shop-catalog-mobile-item--sixth'); sixthSectionsMobileItems.forEach(item => { let sixthTextBlockMobile = item.querySelector('.shop-catalog-mobile-item__text'); if(sixthTextBlockMobile){ sixthTextBlockMobile.classList.remove('shop-catalog-mobile-item__text--active'); } }) } function seventhBlocksMobileClear() { let seventhSectionsMobileItems = document.querySelectorAll('.shop-catalog-mobile-item--seventh'); seventhSectionsMobileItems.forEach(item => { let seventhTextBlockMobile = item.querySelector('.shop-catalog-mobile-item__text'); if(seventhTextBlockMobile){ seventhTextBlockMobile.classList.remove('shop-catalog-mobile-item__text--active'); } }) } //Scroll to up locate in shopCatalogMechMobile function HIDE Sinse 12.4.2021 function scrollUpToTop(){ let scrollUpTotopBlock = document.querySelector('.scroll-up'); if(scrollUpTotopBlock === null){ }else{ scrollUpTotopBlock.style.display = 'none'; } } //change url function changeUrlShopCatalog() { let finalItem = document.querySelectorAll('.final-item'); for(let i = 0; i < finalItem.length; i++){ finalItem[i].addEventListener('click', function(e){ e.preventDefault(); let thisFinalItemHref = this.getAttribute("href"); history.pushState("state", "title", thisFinalItemHref); }) } } function changeUrlShopCatalogMobile(){ let finalItemMobile = document.querySelectorAll('.final-item-mobile'); for(let i = 0; i < finalItemMobile.length; i++){ finalItemMobile[i].addEventListener('click', function(e){ e.preventDefault(); let thisFinalItemHref = this.getAttribute("href"); history.pushState("state", "title", thisFinalItemHref); }) } } function shopCatalogSwitcher(){ // shop-catalog desktop mechanics let shopCatalogSect = document.querySelector('.shop-catalog-desktop'); if(shopCatalogSect === null){ // console.log("shop catalog just left html"); }else { shopCatalogMechDesktop(); shopCatalogFetchDesktop(); shopCatalogMechMobile(); shopCatalogFetchMobile(); changeUrlShopCatalog(); changeUrlShopCatalogMobile(); let footer = document.querySelector('.footer'); footer.style.marginTop = "77px"; } } shopCatalogSwitcher(); function tagLinkModelNoOffersAdaptive(){ let shopCatalogItems = document.querySelectorAll('.shop-catalog-desktop__item'); let shopCatalogItemsSecond = document.querySelectorAll('.shop-catalog-desktop__item--second'); let shopCatalogItemsThird = document.querySelectorAll('.shop-catalog-desktop__item--third'); if(shopCatalogItems === null){ } else{ for(let i = 0; i < shopCatalogItems.length; i++){ let noOffersBlock = shopCatalogItems[i].querySelector('.shop-catalog-desktop__tag-link--model-no-offers'); if(noOffersBlock === null) { }else{ let itemRect = shopCatalogItems[i].getBoundingClientRect(); let itemHeight = itemRect.height; console.log(noOffersBlock); console.log(itemHeight); noOffersBlock.style.minHeight = itemHeight + 'px'; } } for(let i = 0; i < shopCatalogItemsSecond.length; i++){ let noOffersBlock = shopCatalogItemsSecond[i].querySelector('.shop-catalog-desktop__tag-link--model-no-offers'); if(noOffersBlock === null) { }else{ let itemRect = shopCatalogItemsSecond[i].getBoundingClientRect(); let itemHeight = itemRect.height; console.log(noOffersBlock); console.log(itemHeight); noOffersBlock.style.minHeight = itemHeight + 'px'; } } } } //tag-link--model-no-offers replacement link mech in First row (lvl) in catalog function tagLinkNoOffersLinkReplacementFirst() { let catalogItemsFirstRow = document.querySelectorAll('.shop-catalog-desktop__item'); if(catalogItemsFirstRow === null){ }else{ for(let i = 0; i < catalogItemsFirstRow.length; i++){ let tagLinkNoOffersBlockLinkBtn = catalogItemsFirstRow[i].querySelector('.shop-catalog-desktop__tag-link-btn'); let catalogItemsFirstRowLink = catalogItemsFirstRow[i].querySelector('a'); if(tagLinkNoOffersBlockLinkBtn === null){ // console.log('NOT TAG LINK BLOCKS'); }else{ let tagLinkBtnDataLink = tagLinkNoOffersBlockLinkBtn.dataset.link; // console.log(tagLinkBtnDataLink); // console.log(catalogItemsSecondRowLink); delete catalogItemsFirstRowLink.dataset.code; catalogItemsFirstRowLink.href = `http://final.lr.ru${tagLinkBtnDataLink}`; catalogItemsFirstRowLink.addEventListener('click', function(e){ e.preventDefault(); window.location = this.href; }) } } } } //tag-link--model-no-offers replacement link mech in Second row (lvl) in catalog function tagLinkNoOffersLinkReplacementSecond() { let catalogItemsSecondRow = document.querySelectorAll('.shop-catalog-desktop__item--second'); if(catalogItemsSecondRow === null){ }else{ for(let i = 0; i < catalogItemsSecondRow.length; i++){ let tagLinkNoOffersBlockLinkBtn = catalogItemsSecondRow[i].querySelector('.shop-catalog-desktop__tag-link-btn'); let catalogItemsSecondRowLink = catalogItemsSecondRow[i].querySelector('a'); if(tagLinkNoOffersBlockLinkBtn === null){ // console.log('NOT TAG LINK BLOCKS'); }else{ let tagLinkBtnDataLink = tagLinkNoOffersBlockLinkBtn.dataset.link; // console.log(tagLinkBtnDataLink); // console.log(catalogItemsSecondRowLink); delete catalogItemsSecondRowLink.dataset.code; catalogItemsSecondRowLink.href = `http://final.lr.ru${tagLinkBtnDataLink}`; catalogItemsSecondRowLink.addEventListener('click', function(e){ e.preventDefault(); window.location = this.href; }) } } } let catalogMobileItemsSecondRow = document.querySelectorAll('.shop-catalog-mobile-item--second'); if(catalogMobileItemsSecondRow === null){ }else{ for(let i = 0; i < catalogMobileItemsSecondRow.length; i++){ let tagLinkNoOffersBlockLinkBtn = catalogMobileItemsSecondRow[i].querySelector('.shop-catalog-desktop__tag-link-btn'); let catalogMobileItemsSecondRowLink = catalogMobileItemsSecondRow[i].querySelector('a'); if(tagLinkNoOffersBlockLinkBtn === null){ // console.log('NOT TAG LINK BLOCKS'); }else{ let tagLinkBtnDataLink = tagLinkNoOffersBlockLinkBtn.dataset.link; delete catalogMobileItemsSecondRowLink.dataset.code; catalogMobileItemsSecondRowLink.href = `http://final.lr.ru${tagLinkBtnDataLink}`; catalogMobileItemsSecondRowLink.addEventListener('click', function(e){ e.preventDefault(); window.location = this.href; }) } } } } //tag-link--model-no-offers replacement link mech in Third row (lvl) in catalog function tagLinkNoOffersLinkReplacementThird() { let catalogItemsThirdRow = document.querySelectorAll('.shop-catalog-desktop__item--third'); if(catalogItemsThirdRow === null){ }else{ for(let i = 0; i < catalogItemsThirdRow.length; i++){ let tagLinkNoOffersBlockLinkBtn = catalogItemsThirdRow[i].querySelector('.shop-catalog-desktop__tag-link-btn'); let catalogItemsThirdRowLink = catalogItemsThirdRow[i].querySelector('a'); if(tagLinkNoOffersBlockLinkBtn === null){ // console.log('NOT TAG LINK BLOCKS'); }else{ let tagLinkBtnDataLink = tagLinkNoOffersBlockLinkBtn.dataset.link; // console.log(tagLinkBtnDataLink); // console.log(catalogItemsSecondRowLink); delete catalogItemsThirdRowLink.dataset.code; catalogItemsThirdRowLink.href = `http://final.lr.ru${tagLinkBtnDataLink}`; catalogItemsThirdRowLink.addEventListener('click', function(e){ e.preventDefault(); window.location = this.href; }) } } } } //tag-link--model-no-offers replacement link mech in Fourth row (lvl) in catalog function tagLinkNoOffersLinkReplacementFourth() { let catalogItemsThourthRow = document.querySelectorAll('.shop-catalog-desktop__item--fourth'); if(catalogItemsThourthRow === null){ }else{ for(let i = 0; i < catalogItemsThourthRow.length; i++){ let tagLinkNoOffersBlockLinkBtn = catalogItemsThourthRow[i].querySelector('.shop-catalog-desktop__tag-link-btn'); let catalogItemsThourthRowLink = catalogItemsThourthRow[i].querySelector('a'); if(tagLinkNoOffersBlockLinkBtn === null){ // console.log('NOT TAG LINK BLOCKS'); }else{ let tagLinkBtnDataLink = tagLinkNoOffersBlockLinkBtn.dataset.link; // console.log(tagLinkBtnDataLink); // console.log(catalogItemsSecondRowLink); delete catalogItemsThourthRowLink.dataset.code; catalogItemsThourthRowLink.href = `http://final.lr.ru${tagLinkBtnDataLink}`; catalogItemsThourthRowLink.addEventListener('click', function(e){ e.preventDefault(); window.location = this.href; }) } } } } tagLinkNoOffersLinkReplacementFirst(); tagLinkNoOffersLinkReplacementSecond(); tagLinkNoOffersLinkReplacementThird(); tagLinkNoOffersLinkReplacementFourth(); function modelsFastRef(){ let brandParent = document.querySelector('.model-auto__brand-tabbed'); if(brandParent){ let brandInputs = brandParent.querySelectorAll('input'); let brandLabels = brandParent.querySelectorAll('label'); for (let i = 1; i < brandInputs.length; i++) { brandInputs[i].remove(); } for (let i = 1; i < brandLabels.length; i++) { brandLabels[i].remove(); } } } modelsFastRef() function catalogDevSubnavOpen(){ let btnsList = document.querySelectorAll('.catalogDepOpenSubnav'); let catDepNavListParent = document.querySelector('.catalog__departament-navigation-list'); let catDepSection = document.querySelector('.catalog__departament'); if(btnsList === null || catDepNavListParent === null || catDepSection === null){ }else{ let intViewportWidth = window.innerWidth; if(intViewportWidth < 765){ // console.warn("mobile dep"); for(i = 0; i < btnsList.length; i++){ btnsList[i].addEventListener('click', function clickOnBtn(){ if(this.classList.contains('catalogDepOpenSubnav--active')){ navigationButtonRefresh(); subNavMenuRefresh(); this.classList.remove('catalogDepOpenSubnav--active'); }else{ navigationButtonRefresh(); subNavMenuRefresh(); let listOfCurrentBtn = this.querySelector('.catalog__departament-subnavigation-list'); this.classList.add('catalogDepOpenSubnav--active'); let rectOfCurrentBtn = this.getBoundingClientRect(); let departamentTrickBlock = document.createElement('div'); catDepSection.after(departamentTrickBlock); departamentTrickBlock.classList.add('catalog__departament-trick'); departamentTrickBlock.style.top = Math.round(rectOfCurrentBtn.top) + 33 + 'px'; departamentTrickBlock.style.left = Math.round(rectOfCurrentBtn.left) + 'px'; let trickBlockRect = departamentTrickBlock.getBoundingClientRect(); departamentTrickBlock.innerHTML = listOfCurrentBtn.outerHTML; let tricklist = departamentTrickBlock.querySelector('.catalog__departament-subnavigation-list') tricklist.classList.add('catalog__departament-subnavigation-list--active-mobile'); tricklist.style.minWidth = this.offsetWidth + 'px'; tricklist.style.width = 'max-content'; } }); } catDepNavListParent.addEventListener('scroll', function(){ navigationButtonRefresh(); subNavMenuRefresh(); }); window.addEventListener('scroll', function(){ navigationButtonRefresh(); subNavMenuRefresh(); }); }if(intViewportWidth > 766 && intViewportWidth < 1140){ // console.warn("mobile dep"); for(i = 0; i < btnsList.length; i++){ btnsList[i].addEventListener('click', function clickOnBtn(){ if(this.classList.contains('catalogDepOpenSubnav--active')){ navigationButtonRefresh(); subNavMenuRefresh(); this.classList.remove('catalogDepOpenSubnav--active'); }else{ navigationButtonRefresh(); subNavMenuRefresh(); let listOfCurrentBtn = this.querySelector('.catalog__departament-subnavigation-list'); this.classList.add('catalogDepOpenSubnav--active'); let rectOfCurrentBtn = this.getBoundingClientRect(); let departamentTrickBlock = document.createElement('div'); catDepSection.after(departamentTrickBlock); departamentTrickBlock.classList.add('catalog__departament-trick'); departamentTrickBlock.style.top = Math.round(rectOfCurrentBtn.top) + 43 + 'px'; departamentTrickBlock.style.left = Math.round(rectOfCurrentBtn.left) + 'px'; let trickBlockRect = departamentTrickBlock.getBoundingClientRect(); departamentTrickBlock.innerHTML = listOfCurrentBtn.outerHTML; let tricklist = departamentTrickBlock.querySelector('.catalog__departament-subnavigation-list') tricklist.classList.add('catalog__departament-subnavigation-list--active-mobile'); tricklist.style.minWidth = this.offsetWidth + 'px'; tricklist.style.width = 'max-content'; } }); } catDepNavListParent.addEventListener('scroll', function(){ navigationButtonRefresh(); subNavMenuRefresh(); }); window.addEventListener('scroll', function(){ navigationButtonRefresh(); subNavMenuRefresh(); }); }else{ // console.warn("desktop dep"); for(i = 0; i < btnsList.length; i++){ btnsList[i].addEventListener('click', function(e){ if(this.classList.contains('catalogDepOpenSubnav--active')){ let listOfCurrentBtn = this.querySelector('.catalog__departament-subnavigation-list'); this.classList.remove('catalogDepOpenSubnav--active'); listOfCurrentBtn.classList.remove('catalog__departament-subnavigation-list--active'); }else{ subNavMenuRefreshDesktop(); navigationButtonRefresh(); let listOfCurrentBtn = this.querySelector('.catalog__departament-subnavigation-list'); this.classList.add('catalogDepOpenSubnav--active'); listOfCurrentBtn.classList.add('catalog__departament-subnavigation-list--active'); catDepNavListParent.style.overflowX = 'visible'; window.addEventListener('scroll', function(){ subNavMenuRefreshDesktop(); navigationButtonRefresh(); }); document.onclick = function(e){ if(e.target.classList.contains("catalog__departament-navigation-item")){ // console.warn('click inside'); } else { // console.warn('click outside'); subNavMenuRefreshDesktop(); navigationButtonRefresh(); } } } }); } } } } catalogDevSubnavOpen(); function catalogDevSubnavClose(){ let btnsList = document.querySelectorAll('.catalogDepOpenSubnav'); let catDepNavListParent = document.querySelector('.catalog__departament-navigation-list'); let catDepSection = document.querySelector('.catalog__departament'); } function navigationButtonRefresh(){ let NavBtns = document.querySelectorAll('.catalogDepOpenSubnav--active'); NavBtns.forEach(item => { item.classList.remove('catalogDepOpenSubnav--active'); // console.log(item); }) } function subNavMenuRefresh(){ let subNavMenuList = document.querySelectorAll('.catalog__departament-subnavigation-list--active-mobile'); subNavMenuList.forEach(item => { item.classList.remove('catalog__departament-subnavigation-list--active-mobile') }) } function subNavMenuRefreshDesktop(){ let subNavMenuList = document.querySelectorAll('.catalog__departament-subnavigation-list--active'); subNavMenuList.forEach(item => { item.classList.remove('catalog__departament-subnavigation-list--active') }) } function mainPageThirdDepHover(){ let thirdDeps = document.querySelectorAll('.third-departaments__block'); if(thirdDeps !== null){ thirdDeps.forEach(item => { let infoBlock = item.querySelector('.third-departaments__info'); item.addEventListener('mouseover', function(){ infoBlock.classList.add('third-departaments__info--hover'); }) item.addEventListener('mouseout', function(){ infoBlock.classList.remove('third-departaments__info--hover'); }) }); } } mainPageThirdDepHover() //Main model auto mech function modelAutoMech(){ let autoBrandItems = document.querySelectorAll('.model-auto__brand-item'); let autoModelBlocks = document.querySelectorAll('.model-auto__model'); let automodelItems = document.querySelectorAll('.model-auto__model-item'); let autoGenerationBlock = document.querySelectorAll('.model-auto__generation'); let autoGenerationItem = document.querySelectorAll('.model-auto__generation-item'); if (autoBrandItems){ for(let i = 0; i < autoBrandItems.length; i++){ autoBrandItems[i].addEventListener('click', function(){ hideChosenBrandItem(); hideOpenedAutoModelBlocks(); hideChosenAutoModelItem(); hideChosenGenerationBlock(); let currentAutoBrand = this; currentAutoBrand.classList.add('model-auto__brand-item--active'); autoModelBlocks.forEach(item => { if(item.dataset.code == currentAutoBrand.dataset.code){ let currentAutoModelBlock = item; currentAutoModelBlock.style.display = 'block'; } }); }); } for(let i = 0; i < automodelItems.length; i++){ automodelItems[i].addEventListener('click', function(){ hideChosenAutoModelItem(); hideChosenGenerationBlock(); let currentAutoModel = this; currentAutoModel.classList.add('model-auto__model-item--active'); autoGenerationBlock.forEach(item => { if(item.dataset.code === currentAutoModel.dataset.code){ let currentAutoGenerationBlock = item; currentAutoGenerationBlock.style.display = 'block'; } }); }); } //hide items when u switch between cars and track function hideOnSwitchCarsVsTrucks(){ let truckBtn = document.querySelector('label[for="model-tab-type-2"]'); if(truckBtn === null){ } else { truckBtn.addEventListener('click', function(){ hideChosenBrandItem(); hideOpenedAutoModelBlocks(); hideChosenAutoModelItem(); hideChosenGenerationBlock(); }); } } hideOnSwitchCarsVsTrucks(); function hideOnSwitchTrucksVsCars(){ let carBtn = document.querySelector('label[for="model-tab-type-1"]'); if(carBtn === null){ } else { carBtn.addEventListener('click', function(){ hideChosenBrandItem(); hideOpenedAutoModelBlocks(); hideChosenAutoModelItem(); hideChosenGenerationBlock(); }); } } hideOnSwitchTrucksVsCars(); } } modelAutoMech(); function hideChosenBrandItem(){ let autoBrandItems = document.querySelectorAll('.model-auto__brand-item'); autoBrandItems.forEach(item => { item.classList.remove('model-auto__brand-item--active'); }); } function hideOpenedAutoModelBlocks(){ let autoModelBlocks = document.querySelectorAll('.model-auto__model'); autoModelBlocks.forEach(item => { item.style.display = 'none'; }); } function hideChosenAutoModelItem(){ let automodelItems = document.querySelectorAll('.model-auto__model-item'); automodelItems.forEach(item =>{ item.classList.remove('model-auto__model-item--active'); }); } function hideChosenGenerationBlock(){ let autoGenerationBlock = document.querySelectorAll('.model-auto__generation'); autoGenerationBlock.forEach(item => { item.style.display = 'none'; }); } //Generation text hover mech function generationItemTextHover(){ let genItems = document.querySelectorAll('.model-auto__generation-item'); if(genItems){ let intViewportWidth = window.innerWidth; if(intViewportWidth > 1140){ // console.warn('desktop!'); for(let i = 0; i < genItems.length; i++){ genItems[i].addEventListener('mouseover', function(){ let currentText = this.querySelector('.model-auto__generation-item-text'); currentText.classList.add('model-auto__generation-item-text--hover'); }); genItems[i].addEventListener('mouseout', function(){ let currentText = this.querySelector('.model-auto__generation-item-text'); currentText.classList.remove('model-auto__generation-item-text--hover'); }); } } } } generationItemTextHover(); //Mobile scroller help function generationMobileHelpToScroll(){ let brandItem = document.querySelectorAll('.model-auto__brand-item') if(brandItem){ //first lvl let intViewportWidth = window.innerWidth; if(intViewportWidth < 1140){ let brandItemParent = document.querySelector('.model-auto__brand'); brandItem.forEach(item => { item.addEventListener('click', function(){ brandItemParent.scrollIntoView({behavior: "smooth"}); }); }) //second lvl let modelItem = document.querySelectorAll('.model-auto__model-item'); let modelItemParent = document.querySelectorAll('.model-auto__model') modelItem.forEach(item => { item.addEventListener('click', function(){ modelItemParent.forEach(item => { if(window.getComputedStyle(item).display == 'block'){ item.scrollIntoView({behavior: "smooth"}); } }); }); }) }else if(intViewportWidth > 1140){ let brandItemParent = document.querySelector('.model-auto__brand'); brandItem.forEach(item => { item.addEventListener('click', function(){ //Smooth scroll to the proper position const yOffset = -90; const y = brandItemParent.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); }); }) //second lvl let modelItem = document.querySelectorAll('.model-auto__model-item'); let modelItemParent = document.querySelectorAll('.model-auto__model') modelItem.forEach(item => { item.addEventListener('click', function(){ modelItemParent.forEach(item => { if(window.getComputedStyle(item).display == 'block'){ const yOffset = -90; const y = item.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } }); }); }) } } } generationMobileHelpToScroll() function breadCrumbsAutoScroll(){ let listOfBreadItems = document.querySelectorAll('.breadcrumbs > li'); let lastBreadItem = listOfBreadItems[listOfBreadItems.length - 1]; if(listOfBreadItems === null && lastBreadItem === null) { } else{ let intViewportWidth = window.innerWidth; if(intViewportWidth < 1140){ lastBreadItem.scrollIntoView({ block: 'end'}); } else { } } } function stickyHeader(){ let stickyHeader = document.createElement('section'); let body = document.querySelector('body'); let searchPanelFromDesktopHeader = document.querySelector('.search-panel__search'); if(searchPanelFromDesktopHeader === null){ // console.log('header--custom for cart ON'); //empty cart let emptyStateOfCartHeaderItem = document.querySelector('.header-cart-desktop__nav-item--disabled'); if(emptyStateOfCartHeaderItem){ stickyHeader.classList.add('sticky-header'); stickyHeader.innerHTML = ` <!-- sticky header mobile --> <ul class="sticky-header__mobile sticky-header-mobile"> <li class="sticky-header-mobile__item"> <a href="http://final.lr.ru/" class="sticky-header-mobile__link stickyHeaderHomeParent"> <div class="sticky-header-mobile__link-icon-home sticky-header-mobile__link-icon-home"></div> <p class="sticky-header-mobile__link-text sticky-header-mobile__link-text">Главная</p> </a> </li> <li class="sticky-header-mobile__item"> <a href="/departments" class="sticky-header-mobile__link stickyHeaderCatalogParent"> <div class="sticky-header-mobile__link-icon-offers"></div> <p class="sticky-header-mobile__link-text">Каталог</p> </a> </li> <li class="sticky-header-mobile__item"> <a href="/favorite" class="sticky-header-mobile__link stickyHeaderFavoriteParent"> <div class="sticky-header-mobile__link-icon-favorites"></div> <p class="sticky-header-mobile__link-text">Избранное</p> <span style="display: block;">2</span> </a> </li> <li class="sticky-header-mobile__item"> <a href="/cart" class="sticky-header-mobile__link stickyHeaderCartParent"> <div class="sticky-header-mobile__link-icon-cart"></div> <p class="sticky-header-mobile__link-text">Корзина</p> <span style="display: block;">10</span> </a> </li> </ul> <!-- sticky header desktop cart --> <div class="sticky-header__desktop-cart sticky-header-desktop-cart"> <!-- logo --> <a href="http://final.lr.ru/" class="sticky-header-desktop-cart__logo"> <img src="/img/sticky-header/desktop/sticky-header-desktop-logo.svg" alt=""> </a> <!-- nav list --> <ul class="sticky-header-desktop-cart__nav-list header-cart-desktop__nav-list"> <li class="sticky-header-desktop-cart__nav-item header-cart-desktop__nav-item header-cart-desktop__nav-item--current"><a href="https://final.lr.ru/cart/">корзина</a></li> <li class="sticky-header-desktop-cart__nav-item header-cart-desktop__nav-item header-cart-desktop__nav-item--disabled"><a href="https://final.lr.ru/cart/customer">покупатель</a></li> <li class="sticky-header-desktop-cart__nav-item header-cart-desktop__nav-item header-cart-desktop__nav-item--disabled"><a href="https://final.lr.ru/cart/delivery">получение</a></li> <li class="sticky-header-desktop-cart__nav-item header-cart-desktop__nav-item header-cart-desktop__nav-item--disabled"><a href="https://final.lr.ru/cart/payment">оплата</a></li> <li class="sticky-header-desktop-cart__nav-item header-cart-desktop__nav-item header-cart-desktop__nav-item--disabled"><a href="https://final.lr.ru/cart/confirmation">отправить</a></li> </ul> <!-- user --> <div class="sticky-header-desktop-cart__user user"> <a href="/favorite" class="user__favorites"> <img src="/img/favorites-icon.svg" alt=""> <p>Избранное</p> <span style="display: block;">2</span> </a> <a href="/cart" class="user__shopping-cart"> <img src="/img/shopping-cart-icon.svg" alt=""> <p>Корзина</p> <span style="display: block;">10</span> </a> </div> </div> ` body.appendChild(stickyHeader); const stickyHeaderDesktop = document.querySelector('.sticky-header__desktop-cart'); window.addEventListener('scroll', function(e){ let scrollPos = window.scrollY; // console.log(scrollPos); if (scrollPos > 130) { stickyHeaderDesktop.style.top = '0'; } else if(scrollPos < 130){ stickyHeaderDesktop.style.top = '-90px'; } }); }else{ stickyHeader.classList.add('sticky-header'); stickyHeader.innerHTML = ` <!-- sticky header mobile --> <ul class="sticky-header__mobile sticky-header-mobile"> <li class="sticky-header-mobile__item"> <a href="http://final.lr.ru/" class="sticky-header-mobile__link stickyHeaderHomeParent"> <div class="sticky-header-mobile__link-icon-home sticky-header-mobile__link-icon-home"></div> <p class="sticky-header-mobile__link-text sticky-header-mobile__link-text">Главная</p> </a> </li> <li class="sticky-header-mobile__item"> <a href="/departments" class="sticky-header-mobile__link stickyHeaderCatalogParent"> <div class="sticky-header-mobile__link-icon-offers"></div> <p class="sticky-header-mobile__link-text">Каталог</p> </a> </li> <li class="sticky-header-mobile__item"> <a href="/favorite" class="sticky-header-mobile__link stickyHeaderFavoriteParent"> <div class="sticky-header-mobile__link-icon-favorites"></div> <p class="sticky-header-mobile__link-text">Избранное</p> <span style="display: block;">2</span> </a> </li> <li class="sticky-header-mobile__item"> <a href="/cart" class="sticky-header-mobile__link stickyHeaderCartParent"> <div class="sticky-header-mobile__link-icon-cart"></div> <p class="sticky-header-mobile__link-text">Корзина</p> <span style="display: block;">10</span> </a> </li> </ul> <!-- sticky header desktop cart --> <div class="sticky-header__desktop-cart sticky-header-desktop-cart"> <!-- logo --> <a href="http://final.lr.ru/" class="sticky-header-desktop-cart__logo"> <img src="/img/sticky-header/desktop/sticky-header-desktop-logo.svg" alt=""> </a> <!-- nav list --> <ul class="sticky-header-desktop-cart__nav-list header-cart-desktop__nav-list"> <li class="sticky-header-desktop-cart__nav-item header-cart-desktop__nav-item"><a href="/cart/" data-form="shop_order_form_1" onclick="cartFormSubmit('', this)">Корзина</a></li> <li class="sticky-header-desktop-cart__nav-item header-cart-desktop__nav-item"><a href="/cart/customer" data-form="shop_order_form_1" onclick="cartFormSubmit('', this)">Покупатель</a></li> <li class="sticky-header-desktop-cart__nav-item header-cart-desktop__nav-item"><a href="/cart/delivery" data-form="shop_order_form_1" onclick="cartFormSubmit('', this)">Получение</a></li> <li class="sticky-header-desktop-cart__nav-item header-cart-desktop__nav-item"><a href="/cart/payment" data-form="shop_order_form_1" onclick="cartFormSubmit('', this)">Оплата</a></li> <li class="sticky-header-desktop-cart__nav-item header-cart-desktop__nav-item"><a href="/cart/confirmation" data-form="shop_order_form_1" onclick="cartFormSubmit('', this)">Отправить</a></li> </ul> <!-- user --> <div class="sticky-header-desktop-cart__user user"> <a href="/favorite" class="user__favorites"> <img src="/img/favorites-icon.svg" alt=""> <p>Избранное</p> <span style="display: block;">2</span> </a> <a href="/cart" class="user__shopping-cart"> <img src="/img/shopping-cart-icon.svg" alt=""> <p>Корзина</p> <span style="display: block;">10</span> </a> </div> </div> ` body.appendChild(stickyHeader); const stickyHeaderDesktop = document.querySelector('.sticky-header__desktop-cart'); window.addEventListener('scroll', function(e){ let scrollPos = window.scrollY; // console.log(scrollPos); if (scrollPos > 130) { stickyHeaderDesktop.style.top = '0'; } else if(scrollPos < 130){ stickyHeaderDesktop.style.top = '-90px'; } }); function stickyHeaderCartNavigation(){ let stickyHeaderUl = document.querySelector('.sticky-header-desktop-cart__nav-list'); if(stickyHeaderUl){ let stickyNavItems = stickyHeaderUl.querySelectorAll('.header-cart-desktop__nav-item'); if(window.location.toString().includes("https://final.lr.ru/cart/payment")){ console.warn('https://final.lr.ru/cart/payment') for(let i = 0; i < stickyNavItems.length; i++){ stickyNavItems[3].classList.add('header-cart-desktop__nav-item--current'); } }else if(window.location.toString().includes("https://final.lr.ru/cart/delivery")){ console.warn('https://final.lr.ru/cart/delivery') for(let i = 0; i < stickyNavItems.length; i++){ stickyNavItems[2].classList.add('header-cart-desktop__nav-item--current'); } }else if(window.location.toString().includes("https://final.lr.ru/cart/customer")){ console.warn('https://final.lr.ru/cart/customer') for(let i = 0; i < stickyNavItems.length; i++){ stickyNavItems[1].classList.add('header-cart-desktop__nav-item--current'); } }else if(window.location.toString().includes("https://final.lr.ru/cart/confirmation")){ console.warn('https://final.lr.ru/cart/confirmation') for(let i = 0; i < stickyNavItems.length; i++){ stickyNavItems[4].classList.add('header-cart-desktop__nav-item--current'); } }else if(window.location.toString().includes("https://final.lr.ru/cart")){ console.warn('https://final.lr.ru/cart') for(let i = 0; i < stickyNavItems.length; i++){ stickyNavItems[0].classList.add('header-cart-desktop__nav-item--current'); } } } } stickyHeaderCartNavigation(); } }else{ // console.log('default header variation'); if(window.location.toString().includes("https://final.lr.ru/dep")){ stickyHeader.classList.add('sticky-header'); stickyHeader.innerHTML = ` <!-- sticky header mobile --> <ul class="sticky-header__mobile sticky-header-mobile"> <li class="sticky-header-mobile__item"> <a href="http://final.lr.ru/" class="sticky-header-mobile__link stickyHeaderHomeParent" > <div class="sticky-header-mobile__link-icon-home"></div> <p class="sticky-header-mobile__link-text">Главная</p> </a> </li> <li class="sticky-header-mobile__item"> <a href="/departments" class="sticky-header-mobile__link stickyHeaderCatalogParent"> <div class="sticky-header-mobile__link-icon-offers"></div> <p class="sticky-header-mobile__link-text">Каталог</p> </a> </li> <li class="sticky-header-mobile__item"> <a href="/favorite" class="sticky-header-mobile__link stickyHeaderFavoriteParent"> <div class="sticky-header-mobile__link-icon-favorites"></div> <p class="sticky-header-mobile__link-text">Избранное</p> <span>0</span> </a> </li> <li class="sticky-header-mobile__item"> <a href="/cart" class="sticky-header-mobile__link stickyHeaderCartParent"> <div class="sticky-header-mobile__link-icon-cart"></div> <p class="sticky-header-mobile__link-text">Корзина</p> <span>0</span> </a> </li> </ul> <!-- sticky header desktop --> <div class="sticky-header__desktop sticky-header-desktop"> <!-- logo --> <a href="http://final.lr.ru/" class="sticky-header-desktop__logo"> <img src="/img/sticky-header/desktop/sticky-header-desktop-logo.svg" alt=""> </a> <!-- search --> <form class="search-panel__search search" action="/search" method="get"> <input type="text" id="sitesearch-text" class="search__input" name="text" placeholder="Введите запрос.." required=""> <button class="search__setting toggle-settings" type="button"></button> <button class="search__submit" type="submit"></button> <div class="search__modal-wrapper search__modal-wrapper--sticky"> <div class="search__modal"> <div class="search__modal-header"> <b>Настройка поиска</b> Ищем в: </div> <div class="search__modal-body"> <input type="checkbox" id="search__input-name" class="search__input-checkbox" name="search_in_name" value="1" checked="" readonly="readonly" onclick="return false;"> <label for="search__input-name">Наименовании запчасти</label> <input type="checkbox" id="search__input-article" class="search__input-checkbox" name="search_in_number" value="1" checked=""> <label for="search__input-article">Номере запчасти (Артикуле)</label> <button class="search__modal-close" type="submit">OK</button> </div> </div> </div> </form> <!-- user --> <div class="sticky-header-desktop__user user"> <a href="/favorite" class="user__favorites"> <img src="/img/favorites-icon.svg" alt=""> <p>Избранное</p> <span>0</span> </a> <a href="/cart" class="user__shopping-cart" href="cart.html"> <img src="/img/shopping-cart-icon.svg" alt=""> <p>Корзина</p> <span>0</span> </a> </div> <!-- numbers --> <div class="sticky-header-desktop__numbers"> <a href="#" class="sticky-header-desktop__number">+7 (495) 649 60 60</a> <a href="#" class="sticky-header-desktop__number">+7 (495) 649 60 60</a> </div> </div> ` body.appendChild(stickyHeader); const stickyHeaderDesktop = document.querySelector('.sticky-header-desktop'); window.addEventListener('scroll', function(e){ let scrollPos = window.scrollY; // console.log(scrollPos); if (scrollPos > 550) { stickyHeaderDesktop.style.top = '0'; } else if(scrollPos < 550){ stickyHeaderDesktop.style.top = '-90px'; } }); }else { stickyHeader.classList.add('sticky-header'); stickyHeader.innerHTML = ` <!-- sticky header mobile --> <ul class="sticky-header__mobile sticky-header-mobile"> <li class="sticky-header-mobile__item"> <a href="http://final.lr.ru/" class="sticky-header-mobile__link stickyHeaderHomeParent" > <div class="sticky-header-mobile__link-icon-home"></div> <p class="sticky-header-mobile__link-text">Главная</p> </a> </li> <li class="sticky-header-mobile__item"> <a href="/departments" class="sticky-header-mobile__link stickyHeaderCatalogParent"> <div class="sticky-header-mobile__link-icon-offers"></div> <p class="sticky-header-mobile__link-text">Каталог</p> </a> </li> <li class="sticky-header-mobile__item"> <a href="/favorite" class="sticky-header-mobile__link stickyHeaderFavoriteParent"> <div class="sticky-header-mobile__link-icon-favorites"></div> <p class="sticky-header-mobile__link-text">Избранное</p> <span>0</span> </a> </li> <li class="sticky-header-mobile__item"> <a href="/cart" class="sticky-header-mobile__link stickyHeaderCartParent"> <div class="sticky-header-mobile__link-icon-cart"></div> <p class="sticky-header-mobile__link-text">Корзина</p> <span>0</span> </a> </li> </ul> <!-- sticky header desktop --> <div class="sticky-header__desktop sticky-header-desktop"> <!-- logo --> <a href="http://final.lr.ru/" class="sticky-header-desktop__logo"> <img src="/img/sticky-header/desktop/sticky-header-desktop-logo.svg" alt=""> </a> <!-- search --> <form class="search-panel__search search" action="/search" method="get"> <input type="text" id="sitesearch-text" class="search__input" name="text" placeholder="Введите запрос.." required=""> <button class="search__setting toggle-settings" type="button"></button> <button class="search__submit" type="submit"></button> <div class="search__modal-wrapper search__modal-wrapper--sticky"> <div class="search__modal"> <div class="search__modal-header"> <b>Настройка поиска</b> Ищем в: </div> <div class="search__modal-body"> <input type="checkbox" id="search__input-name" class="search__input-checkbox" name="search_in_name" value="1" checked="" readonly="readonly" onclick="return false;"> <label for="search__input-name">Наименовании запчасти</label> <input type="checkbox" id="search__input-article" class="search__input-checkbox" name="search_in_number" value="1" checked=""> <label for="search__input-article">Номере запчасти (Артикуле)</label> <button class="search__modal-close" type="submit">OK</button> </div> </div> </div> </form> <!-- user --> <div class="sticky-header-desktop__user user"> <a href="/favorite" class="user__favorites"> <img src="/img/favorites-icon.svg" alt=""> <p>Избранное</p> <span>0</span> </a> <a href="/cart" class="user__shopping-cart" href="cart.html"> <img src="/img/shopping-cart-icon.svg" alt=""> <p>Корзина</p> <span>0</span> </a> </div> <!-- numbers --> <div class="sticky-header-desktop__numbers"> <a href="#" class="sticky-header-desktop__number">+7 (495) 649 60 60</a> <a href="#" class="sticky-header-desktop__number">+7 (495) 649 60 60</a> </div> </div> ` body.appendChild(stickyHeader); const stickyHeaderDesktop = document.querySelector('.sticky-header-desktop'); window.addEventListener('scroll', function(e){ let scrollPos = window.scrollY; // console.log(scrollPos); if (scrollPos > 130) { stickyHeaderDesktop.style.top = '0'; } else if(scrollPos < 130){ stickyHeaderDesktop.style.top = '-90px'; } }); } } } stickyHeader(); function stickyHeaderMobileDisapearOnBottom(){ let stickyMobile = document.querySelector('.sticky-header-mobile'); if(stickyMobile){ window.addEventListener('scroll', function(e){ if ((window.innerHeight + window.scrollY) >= document.body.scrollHeight) { stickyMobile.style.bottom = '-70px'; }else{ stickyMobile.style.bottom = '0'; } }); } } stickyHeaderMobileDisapearOnBottom(); function stickyHeaderSearchModalDisapear(){ let stickyHeaderDesktop = document.querySelector('.sticky-header__desktop'); if(stickyHeaderDesktop){ let searchModalInsticky = stickyHeaderDesktop.querySelector('.search__modal-wrapper--sticky'); let serachModalSettingBtn = stickyHeaderDesktop.querySelector('.search__setting'); window.addEventListener('scroll', function(e){ let scrollPos = window.scrollY; // console.log(scrollPos); if(scrollPos < 130){ searchModalInsticky.classList.remove('search__modal-wrapper--visible'); serachModalSettingBtn.classList.remove('search__setting--active'); } }); } } stickyHeaderSearchModalDisapear(); //Mobile count updater for catalog update1 function stickyHeaderMobileCartCountUpdate(){ let cartBtnMobileMainHeaderSpan = document.querySelector('.user-mobile__shopping-cart span'); let stickyHeaderCartCounter = document.querySelector('.stickyHeaderCartParent span'); if(cartBtnMobileMainHeaderSpan === null || stickyHeaderCartCounter === null){ // console.log('default header NOT on the page!'); }else{ stickyHeaderCartCounter.innerText = cartBtnMobileMainHeaderSpan.innerText; } } stickyHeaderMobileCartCountUpdate(); //Mobile Favorite count updater for catalog update1 function stickyHeaderMobileFavCountUpdate(){ let favBtnMobileMainHeaderSpan = document.querySelector('.user-mobile__favorites span'); let stickyHeaderFavoriteCounter = document.querySelector('.stickyHeaderFavoriteParent span'); if(favBtnMobileMainHeaderSpan === null || stickyHeaderFavoriteCounter === null){ // console.log('default header NOT on the page!'); }else{ stickyHeaderFavoriteCounter.innerText = favBtnMobileMainHeaderSpan.innerText; } } stickyHeaderMobileFavCountUpdate(); //Desktop count updater for catalog update1 function stickyHeaderDesktopCartCountUpdate(){ let cartBtnDesktopMainHeaderSpan = document.querySelector('.user__shopping-cart span'); let stickyHeaderDesktopCartParent = document.querySelector('.sticky-header-desktop__user'); if(cartBtnDesktopMainHeaderSpan === null || stickyHeaderDesktopCartParent === null){ // console.log('default header NOT on the page!'); }else{ let stickyHeaderCartCounter = stickyHeaderDesktopCartParent.querySelector('.user__shopping-cart span'); stickyHeaderCartCounter.innerText = cartBtnDesktopMainHeaderSpan.innerText; } } stickyHeaderDesktopCartCountUpdate(); //Desktop Favorite count updater for catalog update1 function stickyHeaderDesktopFavoriteCountUpdate(){ // countersHidder(); let favBtnDesktopMainHeaderSpan = document.querySelector('.user__favorites span'); let stickyHeaderDesktopFavParent = document.querySelector('.sticky-header-desktop__user'); if(favBtnDesktopMainHeaderSpan === null || stickyHeaderDesktopFavParent === null){ // console.log('default header NOT on the page!'); }else{ let stickyHeaderFavCounter = stickyHeaderDesktopFavParent.querySelector('.user__favorites span'); stickyHeaderFavCounter.innerText = favBtnDesktopMainHeaderSpan.innerText; } } stickyHeaderDesktopFavoriteCountUpdate(); //MobileUrlReader function stickyHeaderMobileUrlReaderMech(){ let currentUrl let stickyHeaderMobileHomeParent = document.querySelector('.stickyHeaderHomeParent'); let stickyHeaderMobileHomeIcon = stickyHeaderMobileHomeParent.querySelector('.sticky-header-mobile__link-icon-home'); let stickyHeaderMobileHomeText = stickyHeaderMobileHomeParent.querySelector('.sticky-header-mobile__link-text'); let stickyHeaderMobileCatalogParent = document.querySelector('.stickyHeaderCatalogParent'); let stickyHeaderMobileCatalogIcon = stickyHeaderMobileCatalogParent.querySelector('.sticky-header-mobile__link-icon-offers'); let stickyHeaderMobileCatalogText = stickyHeaderMobileCatalogParent.querySelector('.sticky-header-mobile__link-text'); let stickyHeaderMobileCartParent = document.querySelector('.stickyHeaderCartParent'); let stickyHeaderMobileCartIcon = stickyHeaderMobileCartParent.querySelector('.sticky-header-mobile__link-icon-cart'); let stickyHeaderMobileCartText = stickyHeaderMobileCartParent.querySelector('.sticky-header-mobile__link-text'); let stickyHeaderMobileFavoriteParent = document.querySelector('.stickyHeaderFavoriteParent'); let stickyHeaderMobileFavoriteIcon = stickyHeaderMobileFavoriteParent.querySelector('.sticky-header-mobile__link-icon-favorites'); let stickyHeaderMobileFavoriteText = stickyHeaderMobileFavoriteParent.querySelector('.sticky-header-mobile__link-text'); // let stickyHeaderMobileHomeText = stickyHeaderMobileHomeParent.querySelector('.sticky-header-mobile__link-text'); // let stickyHeaderMobileHomeText = stickyHeaderMobileHomeParent.querySelector('.sticky-header-mobile__link-text'); // let stickyHeaderMobileHomeText = stickyHeaderMobileHomeParent.querySelector('.sticky-header-mobile__link-text'); if(window.location.toString().includes("final.lr.ru/favorite")){ // console.warn('This is Favorite PAGE URL'); // console.log(window.location.href); stickyHeaderMobileFavoriteIcon.classList.add('sticky-header-mobile__link-icon-favorites--active'); stickyHeaderMobileFavoriteText.classList.add('sticky-header-mobile__link-text--active'); }else if(window.location.toString().includes("final.lr.ru/dep")){ // console.warn('This is Catalog PAGE URL'); // console.log(window.location.href); stickyHeaderMobileCatalogIcon.classList.add('sticky-header-mobile__link-icon-offers--active'); stickyHeaderMobileCatalogText.classList.add('sticky-header-mobile__link-text--active'); }else if(window.location.toString().includes("final.lr.ru/models")){ // console.warn('This is Catalog PAGE URL'); // console.log(window.location.href); stickyHeaderMobileCatalogIcon.classList.add('sticky-header-mobile__link-icon-offers--active'); stickyHeaderMobileCatalogText.classList.add('sticky-header-mobile__link-text--active'); }else if(window.location.toString().includes("final.lr.ru/cart")){ // console.warn('This is Cart PAGE URL'); // console.log(window.location.href); stickyHeaderMobileCartIcon.classList.add('sticky-header-mobile__link-icon-cart--active'); stickyHeaderMobileCartText.classList.add('sticky-header-mobile__link-text--active'); }else if(window.location.toString().includes("final.lr.ru/")){ // console.warn('This is Home PAGE URL'); // console.log(window.location.href); stickyHeaderMobileHomeIcon.classList.add('sticky-header-mobile__link-icon-home--active'); stickyHeaderMobileHomeText.classList.add('sticky-header-mobile__link-text--active'); } } stickyHeaderMobileUrlReaderMech(); //update on Cart page //Mobile count updater for Cart Page update2 function stickyHeaderMobileCartCountUpdateInCart(){ let cartBtnMobileMainHeaderSpan = document.querySelector('.header-cart-mobile__shopping-cart span'); let stickyHeaderCartCounter = document.querySelector('.stickyHeaderCartParent span'); if(cartBtnMobileMainHeaderSpan === null){ // console.log('default header NOT on the page!'); }else{ stickyHeaderCartCounter.innerText = cartBtnMobileMainHeaderSpan.innerText; } } stickyHeaderMobileCartCountUpdateInCart(); //Mobile Favorite count updater for Cart Page update2 function stickyHeaderMobileFavCountUpdateInCart(){ let favBtnMobileMainHeaderSpan = document.querySelector('.header-cart-mobile__favorites span'); let stickyHeaderFavoriteCounter = document.querySelector('.stickyHeaderFavoriteParent span'); if(favBtnMobileMainHeaderSpan === null){ // console.log('default header NOT on the page!'); }else{ stickyHeaderFavoriteCounter.innerText = favBtnMobileMainHeaderSpan.innerText; } } stickyHeaderMobileFavCountUpdateInCart(); //Desktop count updater for Cart Page update2 function stickyHeaderDesktopCartCountUpdateInCart(){ let cartBtnDesktopMainHeaderSpan = document.querySelector('.header-cart-desktop__shopping-cart span'); let stickyHeaderDesktopCartCounter = document.querySelector('.user__shopping-cart span'); if(cartBtnDesktopMainHeaderSpan === null){ // console.log('default header NOT on the page!'); }else{ stickyHeaderDesktopCartCounter.innerText = cartBtnDesktopMainHeaderSpan.innerText; } } stickyHeaderDesktopCartCountUpdateInCart(); //Desktop Favorite count updater for Cart Page update2 function stickyHeaderDesktopFavoriteCountUpdateInCart(){ let favBtnDesktopMainHeaderSpan = document.querySelector('.header-cart-desktop__favorites span'); let stickyHeaderFavCounter = document.querySelector('.user__favorites span'); if(favBtnDesktopMainHeaderSpan === null){ // console.log('default header NOT on the page!'); }else{ stickyHeaderFavCounter.innerText = favBtnDesktopMainHeaderSpan.innerText; } } stickyHeaderDesktopFavoriteCountUpdateInCart(); //product cards mechs Desktop //Quantity btn cart product card + price/cost values update function cartDesktopProductCardQuantity(){ const desktopProductCard = document.querySelectorAll('.cart-desktop-product'); let desktopCartHeaderSpan = document.querySelector('.header-cart-desktop__shopping-cart span'); //create metaBLock for metaData const body = document.querySelector('body'); const metaBlock = document.createElement('div'); metaBlock.classList.add('metaBlock'); metaBlock.style.visibility = 'hidden'; body.appendChild(metaBlock); if(desktopProductCard === null){ }else{ for(let i = 0; i < desktopProductCard.length; i++){ const desktopProductCardAvailabilityBlock = desktopProductCard[i].querySelector('.cart-desktop-product__shop'); const desktopProductCardQuantityBlock = desktopProductCard[i].querySelector('.cart-desktop-product-quantity'); const desktopProductCardBtnMinus = desktopProductCard[i].querySelector('.cart-desktop-product-quantity__btn-minus'); const desktopProductCardBtnPlus = desktopProductCard[i].querySelector('.cart-desktop-product-quantity__btn-plus'); const desktopProductCardInput = desktopProductCard[i].querySelector('.cart-desktop-product-quantity__default-input'); const desktopProductCardRemoveBtn = desktopProductCard[i].querySelector('.cart-desktop-product__delete'); const parentblock = desktopProductCardQuantityBlock.parentElement; let key = parentblock.dataset.key; let availability = parentblock.dataset.availability; const cartDesktopCustomQuantityBlock = document.createElement('div'); cartDesktopCustomQuantityBlock.classList.add('cart-desktop-product-quantity--custom'); cartDesktopCustomQuantityBlock.innerHTML = ` <div class="cart-desktop-product-quantity__back-btn"></div> <div class="cart-desktop-product-quantity__custom-input-wrapper"> <input class="cart-desktop-product-quantity__custom-input" pattern="[0-9]*" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a class="cart-desktop-product-quantity__apply-btn"></a> </div> `; desktopProductCardQuantityBlock.after(cartDesktopCustomQuantityBlock); //generate nd inject remove-modal function removeModalInject(){ const confirmationRemoveModal = document.createElement('div'); confirmationRemoveModal.classList.add('cart-remove-confirmation-modal'); if(confirmationRemoveModal){ confirmationRemoveModal.innerHTML = ` <div class="cart-remove-confirmation-modal__blur"></div> <div class="cart-remove-confirmation-modal__wrapper"> <div class="cart-remove-confirmation-modal__close"></div> <div class="cart-remove-confirmation-modal__title">Удалить товар</div> <div class="cart-remove-confirmation-modal__text">Вы хотите удалить данный товар? Отменить действие будет невозможно</div> <div class="cart-remove-confirmation-modal__inner"> <div class="cart-remove-confirmation-modal__remove">Удалить</div> <div class="cart-remove-confirmation-modal__back"></div> </div> </div> `; desktopProductCardQuantityBlock.after(confirmationRemoveModal); } } removeModalInject(); const cartDesktopCustomQuantityBackBtn = cartDesktopCustomQuantityBlock.querySelector('.cart-desktop-product-quantity__back-btn'); const cartDesktopCustomQuantityInput = cartDesktopCustomQuantityBlock.querySelector('.cart-desktop-product-quantity__custom-input'); const cartDesktopCustomQuantityRefresh = cartDesktopCustomQuantityBlock.querySelector('.cart-desktop-product-quantity__apply-btn'); const cartRemoveModal = desktopProductCard[i].querySelector('.cart-remove-confirmation-modal'); const cartRemoveModalBlur = desktopProductCard[i].querySelector('.cart-remove-confirmation-modal__blur'); const cartRemoveModalDeleteBtn = desktopProductCard[i].querySelector('.cart-remove-confirmation-modal__remove'); const cartRemoveModalBackBtn = desktopProductCard[i].querySelector('.cart-remove-confirmation-modal__back'); const cartRemoveModalCloseBtn = desktopProductCard[i].querySelector('.cart-remove-confirmation-modal__close'); //Remove Disabled minus if availability is MANY function cartMinusAvailabilityManyFix(){ if(availability === 'много'){ cartMinusBtnReset() } } cartMinusAvailabilityManyFix(); //disable minus btn if input placeholder == '1' function cartMinusBtnDisable(){ const metaCardInput = parentblock.querySelector('.cart-desktop-product-quantity__default-input'); if(metaCardInput.placeholder <= '1'){ if(desktopProductCardBtnMinus === null){ }else{ desktopProductCardBtnMinus.classList.remove('cart-desktop-product-quantity__btn-minus'); desktopProductCardBtnMinus.classList.add('cart-desktop-product-quantity__btn-minus--disable'); } } } cartMinusBtnDisable(); //minus btn disable state reset function cartMinusBtnReset(){ if(desktopProductCardBtnMinus === null){ }else{ desktopProductCardBtnMinus.classList.remove('cart-desktop-product-quantity__btn-minus--disable'); desktopProductCardBtnMinus.classList.add('cart-desktop-product-quantity__btn-minus'); } } //disable plus btn if input placeholder > availability function cartPlusBtnDisable(){ if(desktopProductCardBtnPlus){ desktopProductCardBtnPlus.classList.remove('cart-desktop-product-quantity__btn-plus'); desktopProductCardBtnPlus.classList.add('cart-desktop-product-quantity__btn-plus--disable'); } } //reset plus btn function cartPlusBtnReset(){ desktopProductCardBtnPlus.classList.remove('cart-desktop-product-quantity__btn-plus--disable'); desktopProductCardBtnPlus.classList.add('cart-desktop-product-quantity__btn-plus'); } //check emptiness of cart - if cart empty:reload page function cartDesktopCheckProductList(){ let cartDesktopProductsList = document.querySelector('.cart__desktop-products-inner'); let firstProductInTheList = cartDesktopProductsList.querySelector('li'); if(firstProductInTheList === null){ document.location.reload(); }else{ // console.log('something here, in the cart'); } } function checkAvailabilityBeforeClickCart(){ const metaCardInput = parentblock.querySelector('.cart-desktop-product-quantity__default-input'); const metaCardInputPlaceholder = metaCardInput.placeholder; if(Number(metaCardInputPlaceholder) >= Number(availability)){ //alert desktopProductCardAvailabilityBlock.classList.remove('cart-desktop-product__shop'); desktopProductCardAvailabilityBlock.classList.add('cart-desktop-product__shop--alert'); function cardAvailableAlertDisapear(){ desktopProductCardAvailabilityBlock.classList.remove('cart-desktop-product__shop--alert'); desktopProductCardAvailabilityBlock.classList.add('cart-desktop-product__shop'); } setTimeout(cardAvailableAlertDisapear, 7000); cartPlusBtnDisable(); desktopProductCardInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClickCart(); //quantity button mech -/+/input/inputRefresh if(desktopProductCardBtnMinus){ desktopProductCardBtnMinus.addEventListener('click', desktopProductCardBtnMinusMechFunc, false); function desktopProductCardBtnMinusMechFunc(){ const metaCardInput = parentblock.querySelector('.cart-desktop-product-quantity__default-input'); const metaCardInputPlaceholder = metaCardInput.placeholder; if(metaCardInputPlaceholder == '1'){ cartMinusBtnDisable(); }else{ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('cardProduct MinusClick ajax error'); }else{ // If 1 offer in afterBuyInputBlock checking const response = xhr.response; let countFromCart = response.count; desktopCartHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdateInCart(); trackCartCountInCart(); --desktopProductCardInput.placeholder; cartDesktopCustomQuantityInput.placeholder = desktopProductCardInput.placeholder; cartDesktopCustomQuantityInput.value = desktopProductCardInput.placeholder; cartMinusBtnDisable(); cartPlusBtnReset(); desktopProductCardInput.style.pointerEvents = 'auto'; cartProductCardCostRefresh(); } } xhr.send(params); } } } if(desktopProductCardBtnPlus){ desktopProductCardBtnPlus.addEventListener('click', desktopProductCardBtnPlusMechFunc, false); function desktopProductCardBtnPlusMechFunc(){ const metaCardInput = parentblock.querySelector('.cart-desktop-product-quantity__default-input'); const metaCardInputPlaceholder = metaCardInput.placeholder; cartMinusBtnReset(); //change const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ const response = xhr.response; let countFromCart = response.count; desktopCartHeaderSpan.style.display = 'block'; desktopCartHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdateInCart(); trackCartCountInCart(); ++metaCardInput.placeholder; cartDesktopCustomQuantityInput.placeholder = desktopProductCardInput.placeholder; cartDesktopCustomQuantityInput.value = desktopProductCardInput.placeholder; cartProductCardCostRefresh(); checkAvailabilityBeforeClickCart(); } } xhr.send(params); } } desktopProductCardInput.addEventListener('click', function(){ localStorage.setItem('cartDesktopCustomQuantityInputValue', desktopProductCardInput.placeholder); cartDesktopCustomQuantityInput.value = desktopProductCardInput.placeholder; if(availability == '1'){ //alert desktopProductCardAvailabilityBlock.classList.remove('cart-desktop-product__shop'); desktopProductCardAvailabilityBlock.classList.add('cart-desktop-product__shop--alert'); function cardAvailableAlertDisapear(){ desktopProductCardAvailabilityBlock.classList.remove('cart-desktop-product__shop--alert'); desktopProductCardAvailabilityBlock.classList.add('cart-desktop-product__shop'); } setTimeout(cardAvailableAlertDisapear, 7000); cartPlusBtnDisable(); desktopProductCardInput.style.pointerEvents = 'none'; }else{ desktopProductCardQuantityBlock.style.display = 'none'; cartDesktopCustomQuantityBlock.style.display = 'flex'; cartDesktopCustomQuantityInput.focus(); cartDesktopCustomQuantityInput.addEventListener('input', function updateCustomInputValueCartDesktop(e){ const cartDesktopCustomQuantityInputValue = cartDesktopCustomQuantityInput.value; if(Number(cartDesktopCustomQuantityInputValue) < Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); localStorage.setItem('cartDesktopCustomQuantityInputValue', cartDesktopCustomQuantityInputValue); }else if(Number(cartDesktopCustomQuantityInputValue) > Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); desktopProductCardAvailabilityBlock.classList.remove('cart-desktop-product__shop'); desktopProductCardAvailabilityBlock.classList.add('cart-desktop-product__shop--alert'); function cardAvailableAlertDisapear(){ desktopProductCardAvailabilityBlock.classList.remove('cart-desktop-product__shop--alert'); desktopProductCardAvailabilityBlock.classList.add('cart-desktop-product__shop'); } setTimeout(cardAvailableAlertDisapear, 7000); cartDesktopCustomQuantityInput.value = availability; localStorage.setItem('cartDesktopCustomQuantityInputValue', availability); }else if(typeof availability === 'string'){ localStorage.setItem('cartDesktopCustomQuantityInputValue', cartDesktopCustomQuantityInputValue); } }); cartDesktopCustomQuantityBackBtn.addEventListener('click', function(){ desktopProductCardQuantityBlock.style.display = 'flex'; cartDesktopCustomQuantityBlock.style.display = 'none'; }); } }); cartDesktopCustomQuantityRefresh.addEventListener('click', function(e){ e.preventDefault(); cartMinusBtnReset(); cartDesktopCustomQuantityRefresh.classList.add('cart-desktop-product-quantity__apply-btn--rotate'); function removeRotateClassFromCustomInputDelay(){ cartDesktopCustomQuantityRefresh.classList.remove('cart-desktop-product-quantity__apply-btn--rotate'); } setTimeout(removeRotateClassFromCustomInputDelay, 500); let cartDesktopCustomQuantityInputValue = localStorage.getItem('cartDesktopCustomQuantityInputValue'); if(cartDesktopCustomQuantityInputValue == ''){ // console.warn('cartDesktopCustomQuantityInputValue === empty string'); }else{ const params = new URLSearchParams(); params.set('id', key); params.append('qty', cartDesktopCustomQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('cartDesktopCustomQuantityInputValue ajax error'); } else { // console.warn('cartDesktopCustomQuantityInputValue ajax SUCCESS'); // dynamic data from cart const response = xhr.response; let countFromCart = response.count; desktopCartHeaderSpan.style.display = 'block'; desktopCartHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdateInCart(); trackCartCountInCart(); desktopProductCardInput.placeholder = cartDesktopCustomQuantityInputValue; function customInputSwitchBlocksDelay(){ cartDesktopCustomQuantityBlock.style.display = 'none'; desktopProductCardQuantityBlock.style.display = 'flex'; } setTimeout(customInputSwitchBlocksDelay, 450); cartProductCardCostRefresh(); //clear customInputValue function clearCustomInputValue(){ localStorage.setItem('cartDesktopCustomQuantityInputValue', ''); } setTimeout(clearCustomInputValue, 200); checkAvailabilityBeforeClickCart(); } } xhr.send(params); } }); //remove offer desktopProductCardRemoveBtn.addEventListener('click', function(){ cartRemoveModal.classList.add('cart-remove-confirmation-modal--on'); let cartWrapper = document.querySelectorAll('.cart-remove-confirmation-modal__wrapper'); console.warn(cartWrapper) cartWrapper.forEach(item => { item.style.opacity = '1' }); cartRemoveModalDeleteBtn.addEventListener('click', function(){ let closestSeparator = parentblock.nextElementSibling; const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); }else{ cartRemoveModal.classList.remove('cart-remove-confirmation-modal--on'); const response = xhr.response; let countFromCart = response.count; desktopCartHeaderSpan.style.display = 'block'; desktopCartHeaderSpan.innerText = countFromCart; desktopProductCard[i].style.transition = '0.4s'; desktopProductCard[i].style.transform = 'translate(-130%, 0)'; function parentBlockWithSeparatorDisapear(){ desktopProductCard[i].remove(); closestSeparator.remove(); cartDesktopCheckProductList(); } stickyHeaderDesktopCartCountUpdateInCart(); trackCartCountInCart(); setTimeout(parentBlockWithSeparatorDisapear, 500); setTimeout(cartDesktopStarterPriceRefresh, 600); } } xhr.send(params); }); cartRemoveModalBackBtn.addEventListener('click', function(){ cartRemoveModal.classList.remove('cart-remove-confirmation-modal--on'); }); cartRemoveModalBlur.addEventListener('click', function(){ cartRemoveModal.classList.remove('cart-remove-confirmation-modal--on'); }); cartRemoveModalCloseBtn.addEventListener('click', function(){ cartRemoveModal.classList.remove('cart-remove-confirmation-modal--on'); }); }); //Refresh cost of product card == price * quantity function cartProductCardCostRefresh(){ const desktopProductCardPrice = desktopProductCard[i].querySelector('.cart-desktop-product__price p'); const desktopProductCardCost = desktopProductCard[i].querySelector('.cart-desktop-product__cost p'); const desktopProductCardInput = desktopProductCard[i].querySelector('.cart-desktop-product-quantity__default-input'); const desktopProductCardInputPlaceholder = desktopProductCardInput.placeholder; const desktopProductCardPriceOutput = desktopProductCardPrice.innerText; const desktopProductCardPriceOutputReplaced = desktopProductCardPriceOutput.split(' ').join(''); const desktopProductCardPriceOutputReplacedNumber = Number(desktopProductCardPriceOutputReplaced); const mutantCostInTheRow = desktopProductCardPriceOutputReplacedNumber * Number(desktopProductCardInputPlaceholder); const reMutantCostInTheRowString = mutantCostInTheRow.toString(); const reMutantCostInTheRow = reMutantCostInTheRowString.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); // console.warn('reMutantCostInTheRow') // console.warn(reMutantCostInTheRow) desktopProductCardCost.innerHTML = reMutantCostInTheRow; cartDesktopStarterPriceRefresh() } //refresh starterPrice function cartDesktopStarterPriceRefresh(){ const starterPriceBlocks = document.querySelectorAll('.cart-desktop-starter-price__cost-output'); const finalPriceBlocks = document.querySelectorAll('.cart-final-price__price-output'); const desktopProductCardsCostsList = document.querySelectorAll('.cart-desktop-product__cost p'); metaValueCartCostListCleaner(); desktopProductCardsCostsList.forEach(item => { const desktopProductCardsCostsListItemOutput = item.innerText; const desktopProductCardsCostsListItemOutputReplaced = desktopProductCardsCostsListItemOutput.split(' ').join(''); const desktopProductCardsCostsListItemOutputReplacedNumber = Number(desktopProductCardsCostsListItemOutputReplaced); item.dataset.value = desktopProductCardsCostsListItemOutputReplacedNumber; let cartMetaValueCost = document.createElement('div'); cartMetaValueCost.classList.add('metaValueCartCost'); metaBlock.appendChild(cartMetaValueCost); cartMetaValueCost.innerHTML = item.dataset.value; }) const metaValueCartCostList = document.querySelectorAll('.metaValueCartCost'); //sum of Costs let sumOfCosts = 0; for(let i = 0; i < metaValueCartCostList.length; i++){ let currentMetaValue = metaValueCartCostList[i].innerHTML; let currentMetaValueNumber = Number(currentMetaValue); sumOfCosts += currentMetaValueNumber; } // const starterPriceModified = metaValueCartCostList.reduce((a, b) => a + b, 0); const reMutantSumOfCosts = sumOfCosts.toString(); const reMutantSumOfCostsFormated = reMutantSumOfCosts.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); //replace value of starterPrice and finalPrice blocks starterPriceBlocks.forEach(item => { item.innerHTML = reMutantSumOfCostsFormated; }) finalPriceBlocks.forEach(item => { item.innerHTML = reMutantSumOfCostsFormated; }) } //function for removing metaData from previous iteration function metaValueCartCostListCleaner(){ let metaValueCartCostList = document.querySelectorAll('.metaValueCartCost'); if(metaValueCartCostList === null){ }else{ metaValueCartCostList.forEach(item => { item.remove(); }) } } } } } cartDesktopProductCardQuantity(); //product cards mechs Mobile //Quantity btn cart product card + price/cost values update function cartMobileProductCardQuantity(){ const mobileProductCardList = document.querySelectorAll('.cart-mobile-product'); let mobileCartHeaderSpan = document.querySelector('.header-cart-mobile__shopping-cart span'); //create metaBLock for metaData const body = document.querySelector('body'); const metaBlockMobile = document.createElement('div'); metaBlockMobile.classList.add('metaBlockMobile'); metaBlockMobile.style.visibility = 'hidden'; body.appendChild(metaBlockMobile); if(mobileProductCardList === null){ }else{ for(let i = 0; i < mobileProductCardList.length; i++){ const mobileProductCardAvailabilityBlock = mobileProductCardList[i].querySelector('.cart-mobile-product__shop'); const mobileProductCardQantityBlock = mobileProductCardList[i].querySelector('.cart-mobile-product-quantity'); const mobileProductCardBtnMinus = mobileProductCardList[i].querySelector('.cart-mobile-product-quantity__btn-minus'); const mobileProductCardBtnPlus = mobileProductCardList[i].querySelector('.cart-mobile-product-quantity__btn-plus'); const mobileProductCardInput = mobileProductCardList[i].querySelector('.cart-mobile-product-quantity__default-input'); const mobileProductCardRemoveBtn = mobileProductCardList[i].querySelector('.cart-mobile-product__delete'); const currentMobileproductCard = mobileProductCardList[i]; let key = currentMobileproductCard.dataset.key; let availability = currentMobileproductCard.dataset.availability; const cartMobileCustomQuantityBlock = document.createElement('div'); cartMobileCustomQuantityBlock.classList.add('cart-mobile-product-quantity--custom'); cartMobileCustomQuantityBlock.innerHTML = ` <div class="cart-mobile-product-quantity__back-btn"></div> <div class="cart-mobile-product-quantity__custom-input-wrapper"> <input class="cart-mobile-product-quantity__custom-input" pattern="[0-9]*" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a class="cart-mobile-product-quantity__apply-btn"></a> </div> `; mobileProductCardQantityBlock.after(cartMobileCustomQuantityBlock); //generate nd inject remove-modal mobile function removeModalInjectMobile(){ const confirmationRemoveModal = document.createElement('div'); confirmationRemoveModal.classList.add('cart-remove-confirmation-modal'); if(confirmationRemoveModal){ confirmationRemoveModal.innerHTML = ` <div class="cart-remove-confirmation-modal__blur"></div> <div class="cart-remove-confirmation-modal__wrapper"> <div class="cart-remove-confirmation-modal__close"></div> <div class="cart-remove-confirmation-modal__title">Удалить товар</div> <div class="cart-remove-confirmation-modal__text">Вы хотите удалить данный товар? Отменить действие будет невозможно</div> <div class="cart-remove-confirmation-modal__inner"> <div class="cart-remove-confirmation-modal__remove">Удалить</div> <div class="cart-remove-confirmation-modal__back"></div> </div> </div> `; currentMobileproductCard.appendChild(confirmationRemoveModal); } } removeModalInjectMobile(); const cartMobileCustomQuantityBackBtn = cartMobileCustomQuantityBlock.querySelector('.cart-mobile-product-quantity__back-btn'); const cartMobileCustomQuantityInput = cartMobileCustomQuantityBlock.querySelector('.cart-mobile-product-quantity__custom-input'); const cartMobileCustomQuantityRefresh = cartMobileCustomQuantityBlock.querySelector('.cart-mobile-product-quantity__apply-btn'); const cartRemoveModalMobile = mobileProductCardList[i].querySelector('.cart-remove-confirmation-modal'); const cartRemoveModalBlurMobile = mobileProductCardList[i].querySelector('.cart-remove-confirmation-modal__blur'); const cartRemoveModalDeleteBtnMobile = mobileProductCardList[i].querySelector('.cart-remove-confirmation-modal__remove'); const cartRemoveModalBackBtnMobile = mobileProductCardList[i].querySelector('.cart-remove-confirmation-modal__back'); const cartRemoveModalCloseBtnMobile = mobileProductCardList[i].querySelector('.cart-remove-confirmation-modal__close'); //disable minus btn if input placeholder == '1' function cartMobileMinusBtnDisable(){ const metaCardInput = currentMobileproductCard.querySelector('.cart-mobile-product-quantity__default-input'); if(metaCardInput.placeholder <= '1'){ mobileProductCardBtnMinus.classList.remove('cart-mobile-product-quantity__btn-minus'); mobileProductCardBtnMinus.classList.add('cart-mobile-product-quantity__btn-minus--disable'); } } cartMobileMinusBtnDisable(); //minus btn disable state reset function cartMobileMinusBtnReset(){ mobileProductCardBtnMinus.classList.add('cart-mobile-product-quantity__btn-minus'); mobileProductCardBtnMinus.classList.remove('cart-mobile-product-quantity__btn-minus--disable'); } //disable plus btn if input placeholder > availability function cartMobilePlusBtnDisable(){ mobileProductCardBtnPlus.classList.remove('cart-mobile-product-quantity__btn-plus'); mobileProductCardBtnPlus.classList.add('cart-mobile-product-quantity__btn-plus--disable'); } //reset plus btn function cartMobilePlusBtnReset(){ mobileProductCardBtnPlus.classList.add('cart-mobile-product-quantity__btn-plus'); mobileProductCardBtnPlus.classList.remove('cart-mobile-product-quantity__btn-plus--disable'); } //check emptiness of cart - if cart empty:reload page function cartMobileCheckProductList(){ const cartMobileProductList = document.querySelector('.cart__mobile-products'); const firstProductInTheList = cartMobileProductList.querySelector('li'); if(firstProductInTheList === null){ document.location.reload(); } } function checkAvailabilityBeforeClickCartMobile(){ const metaCardInput = currentMobileproductCard.querySelector('.cart-mobile-product-quantity__default-input'); const metaCardInputPlaceholder = metaCardInput.placeholder; console.warn(availability); if(Number(metaCardInputPlaceholder) >= Number(availability)){ mobileProductCardAvailabilityBlock.classList.remove('cart-mobile-product__shop'); mobileProductCardAvailabilityBlock.classList.add('cart-mobile-product__shop--alert'); function cartMobileCardAvailabilityDisapear(){ mobileProductCardAvailabilityBlock.classList.add('cart-mobile-product__shop'); mobileProductCardAvailabilityBlock.classList.remove('cart-mobile-product__shop--alert'); } setTimeout(cartMobileCardAvailabilityDisapear, 7000); cartMobilePlusBtnDisable(); mobileProductCardInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClickCartMobile(); //quantity button mech -/+/input/inputRefresh mobileProductCardBtnMinus.addEventListener('click', function(){ const metaCardInput = currentMobileproductCard.querySelector('.cart-mobile-product-quantity__default-input'); const metaCardInputPlaceholder = metaCardInput.placeholder; const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('cardProductMobile MinusClick ajax error'); }else{ // If 1 offer in afterBuyInputBlock checking const response = xhr.response; let countFromCart = response.count; mobileCartHeaderSpan.innerText = countFromCart; stickyHeaderMobileCartCountUpdateInCart(); trackCartCountMobileInCart(); --mobileProductCardInput.placeholder; cartMobileCustomQuantityInput.placeholder = mobileProductCardInput.placeholder; cartMobileCustomQuantityInput.value = mobileProductCardInput.placeholder; cartMobileMinusBtnDisable(); cartMobilePlusBtnReset() mobileProductCardInput.style.pointerEvents = 'auto'; cartProductCardCostRefresh(); } } xhr.send(params); }); mobileProductCardBtnPlus.addEventListener('click', function(){ const metaCardInput = currentMobileproductCard.querySelector('.cart-mobile-product-quantity__default-input'); const metaCardInputPlaceholder = metaCardInput.placeholder; cartMobileMinusBtnReset(); //change const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter PlusClick ajax error'); }else{ const response = xhr.response; let countFromCart = response.count; mobileCartHeaderSpan.innerText = countFromCart; stickyHeaderMobileCartCountUpdateInCart(); trackCartCountMobileInCart(); ++mobileProductCardInput.placeholder; cartMobileCustomQuantityInput.placeholder = mobileProductCardInput.placeholder; cartMobileCustomQuantityInput.value = mobileProductCardInput.placeholder; cartProductCardCostRefresh() checkAvailabilityBeforeClickCartMobile(); } } xhr.send(params); }); mobileProductCardInput.addEventListener('click', function(){ localStorage.setItem('cartMobileCustomQuantityInputValue', 'mobileProductCardInput.placeholder'); cartMobileCustomQuantityInput.placeholder = mobileProductCardInput.placeholder; if(availability == '1'){ //alert mobileProductCardAvailabilityBlock.classList.remove('cart-mobile-product__shop'); mobileProductCardAvailabilityBlock.classList.add('cart-mobile-product__shop--alert'); function cartMobileCardAvailabilityDisapear(){ mobileProductCardAvailabilityBlock.classList.add('cart-mobile-product__shop'); mobileProductCardAvailabilityBlock.classList.remove('cart-mobile-product__shop--alert'); } setTimeout(cartMobileCardAvailabilityDisapear, 7000); cartMobilePlusBtnDisable(); mobileProductCardInput.style.pointerEvents = 'none'; }else{ mobileProductCardQantityBlock.style.display = 'none'; cartMobileCustomQuantityBlock.style.display = 'flex'; cartMobileCustomQuantityInput.focus(); cartMobileCustomQuantityInput.addEventListener('input', function updateCustomInputValueCartMobile(e){ const cartMobileCustomQuantityInputValue = cartMobileCustomQuantityInput.value; if(Number(cartMobileCustomQuantityInputValue) < Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); localStorage.setItem('cartMobileCustomQuantityInputValue', cartMobileCustomQuantityInputValue); }else if(Number(cartMobileCustomQuantityInputValue) > Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); mobileProductCardAvailabilityBlock.classList.remove('cart-mobile-product__shop'); mobileProductCardAvailabilityBlock.classList.add('cart-mobile-product__shop--alert'); function cartMobileCardAvailabilityDisapear(){ mobileProductCardAvailabilityBlock.classList.add('cart-mobile-product__shop'); mobileProductCardAvailabilityBlock.classList.remove('cart-mobile-product__shop--alert'); } setTimeout(cartMobileCardAvailabilityDisapear, 7000); cartMobileCustomQuantityInput.value = availability; localStorage.setItem('cartMobileCustomQuantityInputValue', availability); }else if(typeof availability === 'string'){ // console.warn(`КАСТОМНЫЙ ИНПУТ ограничен парметрами инпута - MAX_LENGTH = 3 | ТОВАР ДОБАВЛЯЕМ`); localStorage.setItem('cartMobileCustomQuantityInputValue', cartMobileCustomQuantityInputValue); } }) } }) cartMobileCustomQuantityBackBtn.addEventListener('click', function(){ cartMobileCustomQuantityBlock.style.display = 'none'; mobileProductCardQantityBlock.style.display = 'flex'; }); cartMobileCustomQuantityRefresh.addEventListener('click', function(e){ e.preventDefault(); cartMobileMinusBtnReset(); cartMobileCustomQuantityRefresh.classList.add('cart-mobile-product-quantity__apply-btn--rotate'); function removeRotateClassFromCustomInputDelayMobile(){ cartMobileCustomQuantityRefresh.classList.remove('cart-mobile-product-quantity__apply-btn--rotate'); } setTimeout(removeRotateClassFromCustomInputDelayMobile, 500); let cartMobileCustomQuantityInputValue = localStorage.getItem('cartMobileCustomQuantityInputValue'); if(cartMobileCustomQuantityInputValue == ''){ // console.warn('cartMobileCustomQuantityInputValue === empty string'); }else{ const params = new URLSearchParams(); params.set('id', key); params.append('qty', cartMobileCustomQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('cartMobileCustomQuantityInputValue ajax error'); } else { console.warn('cartMobileCustomQuantityInputValue ajax SUCCESS'); // dynamic data from cart const response = xhr.response; let countFromCart = response.count; mobileCartHeaderSpan.innerText = countFromCart; stickyHeaderMobileCartCountUpdateInCart(); trackCartCountMobileInCart(); mobileProductCardInput.placeholder = cartMobileCustomQuantityInputValue; function customInputSwitchBlocksDelayMobile(){ cartMobileCustomQuantityBlock.style.display = 'none'; mobileProductCardQantityBlock.style.display = 'flex'; } setTimeout(customInputSwitchBlocksDelayMobile, 450); cartProductCardCostRefresh(); //clear customInputValue function clearCustomInputValue(){ localStorage.setItem('cartMobileCustomQuantityInputValue', ''); } setTimeout(clearCustomInputValue, 200); checkAvailabilityBeforeClickCartMobile(); } } xhr.send(params); } }); //remove offer mobileProductCardRemoveBtn.addEventListener('click', function(){ cartRemoveModalMobile.classList.add('cart-remove-confirmation-modal--on'); cartRemoveModalDeleteBtnMobile.addEventListener('click', function(){ cartRemoveModalMobile.classList.remove('cart-remove-confirmation-modal--on'); function deleteProductMobileFunc(){ const closestSeparator = mobileProductCardList[i].nextElementSibling; const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('offerCardInCartMobileDeleteButtonMech ajax error'); }else{ const response = xhr.response; let countFromCart = response.count; mobileCartHeaderSpan.innerText = countFromCart; stickyHeaderMobileCartCountUpdateInCart(); trackCartCountMobileInCart(); mobileProductCardList[i].style.transition = '0.4s'; mobileProductCardList[i].style.transform = 'translate(-130%, 0)'; function parentBlockWithSeparatorDisapear(){ mobileProductCardList[i].remove(); closestSeparator.remove(); cartMobileCheckProductList(); } setTimeout(parentBlockWithSeparatorDisapear, 500); setTimeout(cartMobileStarterPriceRefresh, 600); } } xhr.send(params); } setTimeout(deleteProductMobileFunc, 500); }); cartRemoveModalBackBtnMobile.addEventListener('click', function(){ cartRemoveModalMobile.classList.remove('cart-remove-confirmation-modal--on'); }); cartRemoveModalBlurMobile.addEventListener('click', function(){ cartRemoveModalMobile.classList.remove('cart-remove-confirmation-modal--on'); }); cartRemoveModalCloseBtnMobile.addEventListener('click', function(){ cartRemoveModalMobile.classList.remove('cart-remove-confirmation-modal--on'); }); }); //Refresh cost of product card == price * quantity Mobile function cartProductCardCostRefresh(){ const mobileProductCardPrice = mobileProductCardList[i].querySelector('.cart-mobile-product__price p'); const mobileProductCardCost = mobileProductCardList[i].querySelector('.cart-mobile-product__cost p'); const mobileProductCardInput = mobileProductCardList[i].querySelector('.cart-mobile-product-quantity__default-input'); const mobileProductCardInputPlaceholder = mobileProductCardInput.placeholder; const mobileProductCardPriceOutput = mobileProductCardPrice.innerText; const mobileProductCardPriceOutputReplaced = mobileProductCardPriceOutput.split(' ').join(''); const mobileProductCardPriceOutputReplacedNumber = Number(mobileProductCardPriceOutputReplaced); const mutantCostInTheRow = mobileProductCardPriceOutputReplacedNumber * Number(mobileProductCardInputPlaceholder); const reMutantCostInTheRowToString = mutantCostInTheRow.toString(); const reMutantCostInTheRowFormat = reMutantCostInTheRowToString.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); mobileProductCardCost.innerHTML = reMutantCostInTheRowFormat; cartMobileStarterPriceRefresh(); } //refresh final price after +/-/refresh actions function cartMobileStarterPriceRefresh(){ const starterPriceBlockMobile = document.querySelector('.cart-mobile-starter-price__cost-output'); const finalPriceBlockMobile = document.querySelector('.cart-final-price__price-output'); const mobileProductCardsCostsList = document.querySelectorAll('.cart-mobile-product__cost p'); metaValueCartCostListCleanerMobile(); mobileProductCardsCostsList.forEach(item => { const mobileProductCardsCostsListItemOutput = item.innerText; const mobileProductCardsCostsListItemOutputReplaced = mobileProductCardsCostsListItemOutput.split(' ').join(''); const mobileProductCardsCostsListItemOutputReplacedNumber = Number(mobileProductCardsCostsListItemOutputReplaced); item.dataset.value = mobileProductCardsCostsListItemOutputReplacedNumber; let cartMetaValueCostMobile = document.createElement('div'); cartMetaValueCostMobile.classList.add('metaValueCartCostMobile'); metaBlockMobile.appendChild(cartMetaValueCostMobile); cartMetaValueCostMobile.innerHTML = item.dataset.value; }) const metaValueCartCostListMobile = document.querySelectorAll('.metaValueCartCostMobile'); //sum of Costs let sumOfCosts = 0; for(let i = 0; i < metaValueCartCostListMobile.length; i++){ let currentMetaValue = metaValueCartCostListMobile[i].innerHTML; let currentMetaValueNumber = Number(currentMetaValue); sumOfCosts += currentMetaValueNumber; } const reMutantSumOfCosts = sumOfCosts.toString(); const reMutantSumOfCostsFormated = reMutantSumOfCosts.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); starterPriceBlockMobile.innerHTML = reMutantSumOfCostsFormated; // finalPriceBlockMobile.innerHTML = reMutantSumOfCostsFormated; } //function for removing metaData from previous iteration function metaValueCartCostListCleanerMobile(){ let metaValueCartCostListMobile = document.querySelectorAll('.metaValueCartCostMobile'); if(metaValueCartCostListMobile === null){ }else{ metaValueCartCostListMobile.forEach(item => { item.remove(); }) } } } } } cartMobileProductCardQuantity(); //favoriteMech Desktop function cartDesktopFavBtnMech(){ let favWrapperList = document.querySelectorAll('.cart-desktop-product__favorite-wrapper'); let cartDesktopHeaderFavSpan = document.querySelector('.header-cart-desktop__favorites span'); if(favWrapperList === null){ // console.log('no offers on page'); }else{ for(let i = 0; i < favWrapperList.length; i++){ const currentFavBtn = favWrapperList[i].querySelector('.cart-desktop-product__favorite'); const currentFavBtnActive = favWrapperList[i].querySelector('.cart-desktop-product__favorite-active'); let favBtnKey = currentFavBtn.dataset.key; currentFavBtn.addEventListener('click', function(){ let xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/add'); xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded"); xhr.onload = () => { if (xhr.status === 200) { const jsonResponse = JSON.parse(xhr.responseText);; let countFavFromServer = ++jsonResponse.count; cartDesktopHeaderFavSpan.innerText = countFavFromServer; currentFavBtnActive.style.display = 'block'; // mobileFavoriteTooltip(); stickyHeaderDesktopFavoriteCountUpdateInCart(); trackFavoriteCountInCart(); }else { // console.warn('favoriteMobileMech ajax error'); // errorBannerMobileRemove(); // errorBannerMobile(); } } xhr.send('key=' + favBtnKey); }); currentFavBtnActive.addEventListener('click', function(){ let xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/remove'); xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded"); xhr.onload = () => { if (xhr.status === 200) { const jsonResponse = JSON.parse(xhr.responseText);; let countFavFromServer = --jsonResponse.count; cartDesktopHeaderFavSpan.innerText = countFavFromServer; currentFavBtnActive.style.display = 'none'; currentFavBtn.style.display = 'block'; // mobileFavoriteTooltip(); stickyHeaderDesktopFavoriteCountUpdateInCart(); trackFavoriteCountInCart(); }else { // console.warn('favoriteMobileMech ajax error'); // errorBannerMobileRemove(); // errorBannerMobile(); } } xhr.send('key=' + favBtnKey); }); } } } cartDesktopFavBtnMech(); //favoriteMech Mobile function cartMobileFavBtnMech(){ let favWrapperListMobile = document.querySelectorAll('.cart-mobile-product__favorite-wrapper'); let mobileCartHeaderFavSpan = document.querySelector('.header-cart-mobile__favorites span'); if(favWrapperListMobile === null){ }else{ for (let i = 0; i < favWrapperListMobile.length; i++) { const currentFavBtnMobile = favWrapperListMobile[i].querySelector('.cart-mobile-product__favorite'); const currentFavBtnActiveMobile = favWrapperListMobile[i].querySelector('.cart-mobile-product__favorite-active'); let favBtnKey = currentFavBtnMobile.dataset.key; currentFavBtnMobile.addEventListener('click', function(){ let xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/add'); xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded"); xhr.onload = () => { if (xhr.status === 200) { const jsonResponse = JSON.parse(xhr.responseText);; let countFavFromServer = ++jsonResponse.count; mobileCartHeaderFavSpan.innerText = countFavFromServer; currentFavBtnActiveMobile.style.display = 'block'; // mobileFavoriteTooltip(); stickyHeaderMobileFavCountUpdateInCart(); trackFavoriteCountMobileInCart(); }else { // console.warn('favoriteMobileMech ajax error'); // errorBannerMobileRemove(); // errorBannerMobile(); } } xhr.send('key=' + favBtnKey); }); currentFavBtnActiveMobile.addEventListener('click', function(){ let xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/remove'); xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded"); xhr.onload = () => { if (xhr.status === 200) { const jsonResponse = JSON.parse(xhr.responseText);; let countFavFromServer = jsonResponse.count; mobileCartHeaderFavSpan.innerText = --countFavFromServer; currentFavBtnActiveMobile.style.display = 'none'; currentFavBtnMobile.style.display = 'block'; // mobileFavoriteTooltip(); stickyHeaderMobileFavCountUpdateInCart(); trackFavoriteCountMobileInCart(); }else { // console.warn('favoriteMobileMech ajax error'); // errorBannerMobileRemove(); // errorBannerMobile(); } } xhr.send('key=' + favBtnKey); }); } } } cartMobileFavBtnMech(); //show-hide desktop cart counter in header/sticky-header on cart-page function trackCartCountInCart() { const cartCounterHeader = document.querySelector('.header-cart-desktop__shopping-cart span'); if (cartCounterHeader) { if (cartCounterHeader.innerHTML === '0') { cartCounterHeader.style.display = 'none'; } else { cartCounterHeader.style.display = 'inline-block'; } const cartCounterHeaderSticky = document.querySelector('.user__shopping-cart span'); if (cartCounterHeaderSticky.innerHTML === '0') { cartCounterHeaderSticky.style.display = 'none'; } else { cartCounterHeaderSticky.style.display = 'inline-block'; } } } trackCartCountInCart(); //show-hide mobile cart counter in header/sticky-header on cart-page function trackCartCountMobileInCart() { const cartCountMobileHeader = document.querySelector('.header-cart-mobile__shopping-cart span'); if (cartCountMobileHeader) { const cartCountMobileStickyHeader = document.querySelector('.stickyHeaderCartParent span'); if (cartCountMobileHeader.innerHTML === '0') { cartCountMobileHeader.style.display = 'none'; cartCountMobileStickyHeader.style.display = 'none'; } else { cartCountMobileHeader.style.display = 'inline-block'; cartCountMobileStickyHeader.style.display = 'inline-block'; } } } trackCartCountMobileInCart(); //show-hide desktop favorite counter in header/sticky-header on cart-page function trackFavoriteCountInCart() { const favCountCart = document.querySelector('.header-cart-desktop__favorites span'); if (favCountCart) { const favCountCartSticky = document.querySelector('.user__favorites span'); if (favCountCart.innerHTML === '0') { favCountCart.style.display = 'none'; favCountCartSticky.style.display = 'none'; } else { favCountCart.style.display = 'inline-block'; favCountCartSticky.style.display = 'inline-block'; } } } trackFavoriteCountInCart(); //show-hide desktop favorite counter in header/sticky-header on cart-page function trackFavoriteCountMobileInCart() { const favCountMobile = document.querySelector('.header-cart-mobile__favorites span'); if (favCountMobile) { const favCountMobileSticky = document.querySelector('.stickyHeaderFavoriteParent span'); if (favCountMobile.innerHTML === '0') { favCountMobile.style.display = 'none'; favCountMobileSticky.style.display = 'none'; } else { favCountMobile.style.display = 'inline-block'; favCountMobileSticky.style.display = 'inline-block'; } } } trackFavoriteCountMobileInCart(); //cartDesktopRefreshButtons(); function cartRefreshButtons(){ const refreshBtn = document.querySelector('.cart__refresh-btn'); const refreshBtnFromStarterPriceDesk = document.querySelector('.cart-desktop-starter-price__refresh-btn'); const refreshBtnFromStarterPriceMob = document.querySelector('.cart-mobile-starter-price__refresh-btn'); if(refreshBtn != null) { refreshBtn.addEventListener('click', function(e){ e.preventDefault(); document.location.reload(); return false; }) } if(refreshBtnFromStarterPriceDesk != null) { refreshBtnFromStarterPriceDesk.addEventListener('click', function(e){ e.preventDefault(); document.location.reload(); return false; }) } if(refreshBtnFromStarterPriceMob != null) { refreshBtnFromStarterPriceMob.addEventListener('click', function(e){ e.preventDefault(); document.location.reload(); return false; }) } } cartRefreshButtons(); //mechs for disabled cards function cartDesktopProductDisabledCard(){ const disabledDesktopProductCard = document.querySelectorAll('.cart-desktop-product-disabled'); let desktopCartHeaderSpan = document.querySelector('.header-cart-desktop__shopping-cart span'); //check emptiness of cart function cartDesktopCheckProductList(){ let cartDesktopProductsList = document.querySelector('.cart__desktop-products-inner'); let firstProductInTheList = cartDesktopProductsList.querySelector('li'); if(firstProductInTheList === null){ document.location.reload(); }else{ // console.log('something here, in the cart'); } } if(disabledDesktopProductCard === null){ }else{ for(let i = 0;i < disabledDesktopProductCard.length; i++){ const desktopProductCardFavoriteBtn = disabledDesktopProductCard[i].querySelector('.cart-desktop-product__favorite'); const desktopProductCardRemoveBtn = disabledDesktopProductCard[i].querySelector('.cart-desktop-product__delete'); const desktopProductCardButtonsBlock = disabledDesktopProductCard[i].querySelector('.cart-desktop-product-disabled__action'); const parentblock = desktopProductCardButtonsBlock.parentElement; let key = parentblock.dataset.key; let availability = parentblock.dataset.availability; desktopProductCardRemoveBtn.addEventListener('click', function(){ let closestSeparator = parentblock.nextElementSibling; const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); }else{ const response = xhr.response; let countFromCart = response.count; desktopCartHeaderSpan.style.display = 'block'; desktopCartHeaderSpan.innerText = countFromCart; disabledDesktopProductCard[i].style.transition = '0.4s'; disabledDesktopProductCard[i].style.transform = 'translate(-130%, 0)'; function parentBlockWithSeparatorDisapear(){ disabledDesktopProductCard[i].remove(); closestSeparator.remove(); cartDesktopCheckProductList(); } setTimeout(parentBlockWithSeparatorDisapear, 500); } } xhr.send(params); }); } } } cartDesktopProductDisabledCard(); //trick mechs //trick Mechacnic for radio-buttons in payment choose section function trickMechForRadioButtonsInPaymentSection(){ const paymentRadio = document.querySelectorAll(".cart-payment__select-btn-radio"); if(paymentRadio === null){ // console.log('it`s not cart page!'); }else{ for(let i = 0;i < paymentRadio.length; i++) { if(paymentRadio[i].type=="radio") { paymentRadio[i].onchange=function() { for(let i=0;i<paymentRadio.length;i++) { if(paymentRadio[i].type=="radio") { paymentRadio[i].checked=false; } this.checked=true } } } } } } trickMechForRadioButtonsInPaymentSection(); //green border when radio button checked function trickMechForOptionBlockInPaymentSection(){ const paymentOption = document.querySelectorAll('.cart-payment__option'); if(paymentOption){ for(let i = 0; i < paymentOption.length; i++){ const paymentOptionWrapper = paymentOption[i].querySelector('.cart-payment__option-info-wrapper'); const paymentOptionRadioButton = paymentOption[i].querySelector('.cart-payment__select-btn'); const paymentOptionRadioButtonInput = paymentOption[i].querySelector('.cart-payment__select-btn input'); paymentOptionRadioButton.addEventListener('click', function(){ const allPaymentOptionWrapper = document.querySelectorAll('.cart-payment__option-info-wrapper'); allPaymentOptionWrapper.forEach(item => { item.classList.remove('cart-payment__option-info-wrapper--active'); }) paymentOptionWrapper.classList.add('cart-payment__option-info-wrapper--active'); }); if(paymentOptionRadioButtonInput.checked){ paymentOptionWrapper.classList.add('cart-payment__option-info-wrapper--active'); } } } } trickMechForOptionBlockInPaymentSection(); //green border when radio button checked function trickMechForOptionBlockInDeliverySection(){ const deliveryOption = document.querySelectorAll('.cart-delivery__option'); if(deliveryOption === null){ // console.log('no deliveryOptions'); }else{ for(let i = 0; i < deliveryOption.length; i++){ const deliveryOptionWrapper = deliveryOption[i].querySelector('.cart-delivery__option-info-wrapper'); const deliveryOptionRadioButton = deliveryOption[i].querySelector('.cart-delivery__select-btn input'); console.warn('deliveryOptionRadioButton'); console.warn(deliveryOptionRadioButton); deliveryOptionRadioButton.addEventListener('click', function(){ const allDeliveryOptionWrapper = document.querySelectorAll('.cart-delivery__option-info-wrapper'); allDeliveryOptionWrapper.forEach(item => { item.classList.remove('cart-delivery__option-info-wrapper--active'); }) deliveryOptionWrapper.classList.add('cart-delivery__option-info-wrapper--active'); }); //if button checked on load if(deliveryOptionRadioButton.checked){ deliveryOptionWrapper.classList.add('cart-delivery__option-info-wrapper--active'); } } } } trickMechForOptionBlockInDeliverySection() //trick Mechacnic for radio-buttons in delivery choose section function trickMechForRadioButtonsInDeliverySection(){ const deliveryRadio = document.querySelectorAll(".cart-delivery__select-btn-radio"); if(deliveryRadio === null){ // console.log('it`s not cart page!'); }else{ for(let i = 0;i < deliveryRadio.length; i++) { if(deliveryRadio[i].type=="radio") { deliveryRadio[i].onchange=function() { for(let i=0;i<deliveryRadio.length;i++) { if(deliveryRadio[i].type=="radio") { deliveryRadio[i].checked=false; } this.checked=true } } } } } } trickMechForRadioButtonsInDeliverySection(); //YA maps mobile button link function yaMapMobileLink(){ const yaIframe = document.querySelector('iframe'); const deliveryTabContent = document.querySelector('.cart-delivery__moscow-pickup-wrapper'); console.warn('yaIframe') console.warn(yaIframe) if(deliveryTabContent){ let metaMobileButton = document.createElement('a'); metaMobileButton.classList.add('yaFrameBtnMeta'); deliveryTabContent.insertBefore(metaMobileButton, yaIframe); metaMobileButton.href = 'yandexmaps://http://maps.yandex.ru/213/moscow/?ll=37.416902%2C55.712214&pt=37.415748%2C55.713659&z=17.1'; } } //cart-delivery cart-delivery__option-inner MARGIN without TITLE function cartDeliveryOptionInnerWithOutTitleMargin(){ const optionInners = document.querySelectorAll('.cart-delivery__option-inner'); if(optionInners){ let intViewportWidth = window.innerWidth; if(intViewportWidth > 1100){ optionInners.forEach( item => { const optionInnerTitle = item.querySelector('.cart-delivery__option-info-title'); const optionInnerInfo = item.querySelector('.cart-delivery__info'); if(optionInnerTitle === null){ optionInnerInfo.style.margin = "0px 0 0 25px"; } }); } } } cartDeliveryOptionInnerWithOutTitleMargin(); //DADATA funcs //DADATA.RU Find with INN для ИП *12 символов function findDataFromInnForIp(){ const firstTabcontentBlock = document.querySelector('.cart-customer__radio-btn-content-1'); if(firstTabcontentBlock){ let firstInnInput = firstTabcontentBlock.querySelector('.cart-customer-organisation-data__input-inn'); let secondOrganizationNameInput = firstTabcontentBlock.querySelector('.cart-customer-organisation-data__input-organization-name'); let thirdAdressInput = firstTabcontentBlock.querySelector('.cart-customer-organisation-data__input-address'); let firstInnHint = firstTabcontentBlock.querySelector('.cart-customer-organisation-data__input-hint'); firstInnInput.addEventListener('change', function(e){ if(firstInnInput.value.length !== 12){ firstInnHint.innerHTML = `Некорректная длинна ИНН`; firstInnInput.classList.add('cart-customer-organisation-data__input-field--alert'); function removeFirstInnInputAlertDelay(){ firstInnInput.classList.remove('cart-customer-organisation-data__input-field--alert'); firstInnHint.innerHTML = `Введите ИНН, и мы найдем Вашу организацию`; } setTimeout(removeFirstInnInputAlertDelay, 5000); }else{ let url = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/findById/party"; let token = "7d7a4b089cea1b122a5a6e748afc75458f420444"; let query = firstInnInput.value; let options = { method: "POST", mode: "cors", headers: { "Content-Type": "application/json", "Accept": "application/json", "Authorization": "Token " + token }, body: JSON.stringify({query: query}) } fetch(url, options) .then(response => response.json()) .then((data) => { let address = data.suggestions[0].data.address.value; let ipOrganization = data.suggestions[0].value; console.log(data); // thirdAdressInput.value = address; secondOrganizationNameInput.value = ipOrganization; }) .catch(error => { firstInnHint.innerHTML = `Проверьте правильность введенных данных`; firstInnInput.classList.add('cart-customer-organisation-data__input-field--alert'); function removeFirstInnInputAlertDelay(){ firstInnInput.classList.remove('cart-customer-organisation-data__input-field--alert'); firstInnHint.innerHTML = `Введите ИНН, и мы найдем Вашу организацию`; } setTimeout(removeFirstInnInputAlertDelay, 5000); }); } }); } } findDataFromInnForIp(); //DADATA.RU Find with INN для ЮР Лиц *10 символов function findDataFromInnForUr(){ const secondTabcontentBlock = document.querySelector('.cart-customer__radio-btn-content-2'); if(secondTabcontentBlock){ let firstInnInput = secondTabcontentBlock.querySelector('.cart-customer-organisation-data__input-inn'); let secondKppInput = secondTabcontentBlock.querySelector('.cart-customer-organisation-data__input-kpp'); let thirdOrganizationNameInput = secondTabcontentBlock.querySelector('.cart-customer-organisation-data__input-organization-name'); let fourthAdressInput = secondTabcontentBlock.querySelector('.cart-customer-organisation-data__input-address'); let firstInnHint = secondTabcontentBlock.querySelector('.cart-customer-organisation-data__input-hint'); firstInnInput.addEventListener('change', function(e){ if(firstInnInput.value.length !== 10){ firstInnHint.innerHTML = `Некорректная длинна ИНН`; firstInnInput.classList.add('cart-customer-organisation-data__input-field--alert'); function removeFirstInnInputAlertDelay(){ firstInnInput.classList.remove('cart-customer-organisation-data__input-field--alert'); firstInnHint.innerHTML = `Введите ИНН, и мы найдем Вашу организацию`; } setTimeout(removeFirstInnInputAlertDelay, 5000); }else{ let url = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/findById/party"; let token = "7d7a4b089cea1b122a5a6e748afc75458f420444"; let query = firstInnInput.value; let options = { method: "POST", mode: "cors", headers: { "Content-Type": "application/json", "Accept": "application/json", "Authorization": "Token " + token }, body: JSON.stringify({query: query}) } fetch(url, options) .then(response => response.json()) .then((data) => { let kpp = data.suggestions[0].data.kpp; let address = data.suggestions[0].data.address.value; let organizationName = data.suggestions[0].data.name.full; console.log(data); secondKppInput.value = kpp; thirdOrganizationNameInput.value = organizationName; fourthAdressInput.value = address; }) .catch(error => { firstInnHint.innerHTML = `Проверьте правильность введенных данных`; firstInnInput.classList.add('cart-customer-organisation-data__input-field--alert'); function removeFirstInnInputAlertDelay(){ firstInnInput.classList.remove('cart-customer-organisation-data__input-field--alert'); firstInnHint.innerHTML = `Введите ИНН, и мы найдем Вашу организацию`; } setTimeout(removeFirstInnInputAlertDelay, 5000); }); } }); } } findDataFromInnForUr(); //DADATA.RU Find With BIK on Customer page || 1 func instead of 2 function findDataFromBikCustomerPage(){ let firstBikInput = document.querySelector('.cart-customer-payment-details-data__input-bik'); if(firstBikInput){ let secondBankInput = document.querySelector('.cart-customer-payment-details-data__input-bank'); let thirdCorrespondentAccountInput = document.querySelector('.cart-customer-payment-details-data__input-correspondent-account'); let firstBikHint = document.querySelector('.cart-customer-payment-details-data__input-hint-bik'); firstBikInput.addEventListener('change', function(){ if(firstBikInput.value.length !== 9){ firstBikHint.innerHTML = `Некорректная длинна БИК`; firstBikInput.classList.add('cart-customer-payment-details-data__input-field--alert'); function removeFirstInnInputAlertDelay(){ firstBikInput.classList.remove('cart-customer-payment-details-data__input-field--alert'); firstBikHint.innerHTML = `Введите БИК, и мы найдем Ваш банк`; } setTimeout(removeFirstInnInputAlertDelay, 5000); }else{ let url = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/findById/bank"; let token = "7d7a4b089cea1b122a5a6e748afc75458f420444"; let query = firstBikInput.value; let options = { method: "POST", mode: "cors", headers: { "Content-Type": "application/json", "Accept": "application/json", "Authorization": "Token " + token }, body: JSON.stringify({query: query}) } fetch(url, options) .then(response => response.json()) .then((data) => { console.log(data); let bank = data.suggestions[0].value; let correspondentAccount = data.suggestions[0].data.correspondent_account; secondBankInput.value = bank; thirdCorrespondentAccountInput.value = correspondentAccount; }) .catch(error => { firstBikHint.innerHTML = `Проверьте правильность введенных данных`; firstBikInput.classList.add('cart-customer-payment-details-data__input-field--alert'); function removeFirstInnInputAlertDelay(){ firstBikInput.classList.remove('cart-customer-payment-details-data__input-field--alert'); firstBikHint.innerHTML = `Введите БИК, и мы найдем Ваш банк`; } setTimeout(removeFirstInnInputAlertDelay, 5000); }); } }); } } findDataFromBikCustomerPage(); //DADATA.ru Tooltip about banks function findDataAboutBank(){ let firstBikInput = document.querySelector('#shoporder-legal_bank'); if(firstBikInput){ firstBikInput.addEventListener('change', function(){ let url = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/bank"; let token = "7d7a4b089cea1b122a5a6e748afc75458f420444"; let query = firstBikInput.value; let options = { method: "POST", mode: "cors", headers: { "Content-Type": "application/json", "Accept": "application/json", "Authorization": "Token " + token }, body: JSON.stringify({query: query}) } fetch(url, options) .then(response => response.json()) .then(result => console.log(result)) .catch(error => console.log("error", error)); }); } } // findDataAboutBank() //mobile header closer function toggleHiddenMenuBtnCart() { let hiddenMenuBtnCart = document.querySelector('.header-cart-mobile__hamburger-btn-icon'); let hiddenMenuCart = document.querySelector('.header-cart-mobile__hamburger-menu'); let headerCart = document.querySelector('.header-cart'); let body = document.querySelector('body'); if (hiddenMenuBtnCart){ let glassBackground = document.createElement("div"); glassBackground.classList.add('header-blur-wrap'); headerCart.after(glassBackground); hiddenMenuBtnCart.addEventListener('click', function () { this.classList.toggle('active'); hiddenMenuCart.style.display = 'flex'; function delayTramsition(){ hiddenMenuCart.classList.toggle('header-cart-mobile__hamburger-menu--on'); glassBackground.classList.toggle('header-blur-wrap--on'); body.classList.toggle('page-body__no-scroll'); } setTimeout(delayTramsition, 50); }); glassBackground.addEventListener('click', function () { hiddenMenuBtnCart.classList.remove('active'); hiddenMenuCart.style.display = 'none'; function delayTramsition(){ hiddenMenuCart.classList.remove('header-cart-mobile__hamburger-menu--on'); glassBackground.classList.remove('header-blur-wrap--on'); body.classList.remove('page-body__no-scroll'); } setTimeout(delayTramsition, 50); }); //close blocks on document cliks function handleClick(event) { const target = event.target; const isClickedOnExcludedBlock = target.matches('.header-cart-mobile__hamburger-btn-icon, .header-cart-mobile__hamburger-menu, .hbc-line, .header-cart-mobile__hamburger-link a, .header-cart-mobile__hamburger-call-btn, .user-wrapper__hidden-menu'); if (!isClickedOnExcludedBlock) { hiddenMenuBtnCart.classList.remove('active'); hiddenMenuCart.style.display = 'none'; function delayTramsition(){ hiddenMenuCart.classList.remove('header-cart-mobile__hamburger-menu--on'); glassBackground.classList.remove('header-blur-wrap--on'); body.classList.remove('page-body__no-scroll'); } setTimeout(delayTramsition, 50); } } document.addEventListener('click', handleClick); } } toggleHiddenMenuBtnCart(); function headerContactUsModalCart() { let contactUsModal = document.querySelector('.header-contact-us'); let contactUsModalWrapper = document.querySelector('.header-contact-us__wrapper'); let contactUsModalClose = document.querySelector('.header-contact-us__close'); let contactUsMobileHeaderNumber = document.querySelector('.header-cart-mobile__phone'); let contactUsDesktopHeaderNumbers = document.querySelectorAll('.header-cart-desktop__number'); let contactUsHeaderMobileHidden = document.querySelector('.header-cart-mobile__hamburger-call-btn'); let contactUsHeaderGlassBack = document.querySelector('.header-contact-us__blur'); let body = document.querySelector('body'); function openContactUsModal(e) { if (e) e.preventDefault(); contactUsModal.style.display = 'block'; body.classList.add('page-body__no-scroll'); contactUsModalWrapper.classList.add('header-contact-us__wrapper--opening'); } function closeContactUsModal() { contactUsModalWrapper.classList.remove('header-contact-us__wrapper--opening'); contactUsModalWrapper.classList.add('header-contact-us__wrapper--closing'); const handleAnimationEnd = function() { contactUsModal.style.display = 'none'; body.classList.remove('page-body__no-scroll'); contactUsModalWrapper.classList.remove('header-contact-us__wrapper--closing'); contactUsModalWrapper.removeEventListener('animationend', handleAnimationEnd); }; contactUsModalWrapper.addEventListener('animationend', handleAnimationEnd); } if (contactUsDesktopHeaderNumbers) { contactUsDesktopHeaderNumbers.forEach(number => number.addEventListener('click', openContactUsModal)); if (contactUsHeaderMobileHidden) { contactUsHeaderMobileHidden.addEventListener('click', openContactUsModal); // Раскомментируйте следующий блок, если нужно активировать эту функциональность // if (contactUsMobileHeaderNumber) { // contactUsMobileHeaderNumber.addEventListener('click', openContactUsModal); // } if (contactUsModalClose) { contactUsModalClose.addEventListener('click', closeContactUsModal); contactUsHeaderGlassBack.addEventListener('click', closeContactUsModal); } } } } headerContactUsModalCart(); //Dadata autoComplete in Cart //delievery city input #first in the list function dadataAutoCityInCartDelivery(){ //jquery to dadata const scriptCartMoscowDadataJquery = document.createElement('script'); scriptCartMoscowDadataJquery.async = false; scriptCartMoscowDadataJquery.innerHTML = ` jQuery(document).ready(function($){ let token = "7d7a4b089cea1b122a5a6e748afc75458f420444"; let type = "address"; let $city = $("#shoporder-delivery_city"); let $address = $("#address") ; function iplocate() { let serviceUrl = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address"; let params = { type: "GET", contentType: "application/json", headers: { "Authorization": "Token " + token } }; return $.ajax(serviceUrl, params); } var defaultFormatResult = $.Suggestions.prototype.formatResult; function formatResult(value, currentValue, suggestion, options) { var newValue = suggestion.data.city; suggestion.value = newValue; return defaultFormatResult.call(this, newValue, currentValue, suggestion, options); } function formatSelected(suggestion) { return suggestion.data.city; } // город и населенный пункт $city.suggestions({ token: token, type: "ADDRESS", hint: false, bounds: "city", constraints: { locations: { city_type_full: "город" } }, formatResult: formatResult, formatSelected: formatSelected, onSelect: function(suggestion) { console.log(suggestion); } }); disableAutocomplete(); // console.warn( '$city.suggestions ') // console.warn( $city.suggestions() ) }); `; document.body.appendChild(scriptCartMoscowDadataJquery); } dadataAutoCityInCartDelivery(); function disableAutocomplete() { $("form#w0 :input").each(function(){ var input = $(this); if($(this).attr("autocomplete") == 'new-password') { $(this).attr("autocomplete", 'off'); } }); } //dadata by Igor function dadataDynamicCartDeliveryAddress(){ document.addEventListener('DOMContentLoaded', function(){ var token = "7d7a4b089cea1b122a5a6e748afc75458f420444"; function none() { $("#shoporder-delivery_city").suggestions({ token: token, type: "ADDRESS", bounds: "city", constraints: { locations: { city_type_full: "город" } }, geoLocation: false, onSelect: enforceRegion }); } function msk() { $("#shoporder-delivery_address").suggestions({ token: token, type: "ADDRESS", constraints: { locations: { region: "Москва" }, }, // в списке подсказок не показываем область restrict_value: true, onSelect: enforceIndex, }); } $("input[name='ShopOrder[delivery_type_id]']").on("change", function() { if($(this).val() == 7) { $("#shoporder-delivery_address").val(""); $("#shoporder-delivery_index").val(""); $("#shoporder-delivery_apartment").val(""); window[msk()]; } else { $("#shoporder-delivery_city").val(""); $("#shoporder-delivery_address").val(""); $("#shoporder-delivery_index").val(""); $("#shoporder-delivery_apartment").val(""); window[none()]; } }); function enforceRegion(suggestion) { console.log(suggestion); var sgt = $("#shoporder-delivery_address").suggestions(); sgt.clear(); sgt.setOptions({ constraints: { locations: { kladr_id: suggestion.data.kladr_id } }, restrict_value: true, onSelect: enforceIndex, }); }; function enforceIndex(suggestion) { $("#shoporder-delivery_index").val(suggestion.data.postal_code); } $("#shoporder-delivery_address").suggestions({ token: token, type: "ADDRESS" }); }) } dadataDynamicCartDeliveryAddress(); //recommended-installation-service activete function recommendedInstallServiceActivation(){ let installationBtnInner = document.querySelector('.recommended-installation-service__btn-inner'); if(installationBtnInner){ let hiddenInput = installationBtnInner.querySelector('input'); let installationBtn = installationBtnInner.querySelector('.recommended-installation-service__btn'); installationBtn.addEventListener('click', function(e){ e.preventDefault(); installationBtn.classList.toggle('recommended-installation-service__btn--active'); // hiddenInput.value = 1; function toggleInputValue(){ if(hiddenInput.value == '0'){ console.warn('INPUT VALUE = 0'); hiddenInput.value = 1; }else{ console.warn('INPUT VALUE = 1'); hiddenInput.value = 0; } } toggleInputValue() }); } } recommendedInstallServiceActivation(); //show of city = Mcs function recommendedInstallServiceShow(){ const dadataModalSuccessConfirmCity = localStorage.getItem('dadataModalSuccessConfirmCity'); const serviceBlock = document.querySelector('.recommended-installation-service'); const serviceBlockConfirm = document.querySelector('.cart-confirmation__service-inner'); if(serviceBlock){ if(dadataModalSuccessConfirmCity && dadataModalSuccessConfirmCity == 'Москва'){ serviceBlock.style.display = 'block'; }else{ serviceBlock.style.display = 'none'; } } if(serviceBlockConfirm){ if( dadataModalSuccessConfirmCity && dadataModalSuccessConfirmCity == 'Москва'){ serviceBlockConfirm.style.display = 'block'; }else{ serviceBlockConfirm.style.display = 'none'; } } } recommendedInstallServiceShow(); //payment tabs width function paymentTabsDynamicWidth(){ const paymentTabs = document.querySelectorAll('.cart-payment__tab-label'); const paymentTabsInput = document.querySelectorAll('.cart-payment__tab-input'); let intViewportWidth = window.innerWidth; if(paymentTabs !== null){ // console.warn(paymentTabsInput.length) if(paymentTabsInput[0]){ if(paymentTabsInput[0].checked){ // console.warn('first tab checked'); }else if(paymentTabsInput[1].checked){ // console.warn('second tab checked'); }else if(paymentTabsInput[2].checked){ // console.warn('third tab checked'); }else{ setTimeout(() => paymentTabsInput[0].click(), 230); } } if(intViewportWidth > 768 && intViewportWidth < 1140){ // console.warn('768') if(paymentTabs.length == '4'){ paymentTabs.forEach(item => { item.style.width = '24.5%'; }); } }else if(intViewportWidth > 1140 && intViewportWidth < 1440){ // console.warn('1140') if(paymentTabs.length == '4'){ paymentTabs.forEach(item => { item.style.width = '24.7%'; }); } }else if(intViewportWidth > 1440 && intViewportWidth < 1800){ // console.warn('1440') if(paymentTabs.length == '4'){ paymentTabs.forEach(item => { item.style.width = '24.75%'; }); } }else if(intViewportWidth > 1800 && intViewportWidth < 2000){ // console.warn('1800') if(paymentTabs.length == '4'){ paymentTabs.forEach(item => { item.style.width = '24.8%'; }); } } } } paymentTabsDynamicWidth() //delivery tabs width function deliveryTabsDynamicWidth(){ const deliveryTabs = document.querySelectorAll('.cart-delivery__tab-label'); let intViewportWidth = window.innerWidth; if(deliveryTabs !== null){ if(intViewportWidth > 768 && intViewportWidth < 1140){ // console.warn('768') if(deliveryTabs.length == '4'){ deliveryTabs.forEach(item => { item.style.width = '24.5%'; }); } }else if(intViewportWidth > 1140 && intViewportWidth < 1440){ // console.warn('1140') if(deliveryTabs.length == '4'){ deliveryTabs.forEach(item => { item.style.width = '24.7%'; }); } }else if(intViewportWidth > 1440 && intViewportWidth < 1800){ // console.warn('1440') if(deliveryTabs.length == '4'){ deliveryTabs.forEach(item => { item.style.width = '24.75%'; }); } }else if(intViewportWidth > 1800 && intViewportWidth < 2000){ // console.warn('1800') if(deliveryTabs.length == '4'){ deliveryTabs.forEach(item => { item.style.width = '24.8%'; }); } } } } deliveryTabsDynamicWidth(); function deliveryFromMoscowYandexMap(){ const nextBlockAfterMapWithBtn = document.querySelector('.cart-delivery__tabcontent-inner'); if(nextBlockAfterMapWithBtn){ const moscowPickUp = document.createElement('div'); moscowPickUp.classList.add('cart-delivery__moscow-pickup-wrapper'); moscowPickUp.innerHTML = `<iframe src="https://yandex.ru/map-widget/v1/?lang=ru_RU&scroll=true&um=constructor%3AxeGkuqkCh00FYennh6BMWBHXDjkCF5rA" frameborder="0" allowfullscreen="true" width="100%" height="100%" style="display: block;"></iframe>`; nextBlockAfterMapWithBtn.before(moscowPickUp); setTimeout(yaMapMobileLink, 500); } } //delivery tabs dynamically click/clicked function deliveryTabsMech(){ const deliveryTabs = document.querySelectorAll('.cart-delivery__tab-input'); const primaryDataParent = document.querySelector('.cart-delivery__primary-data'); if(deliveryTabs !== null && primaryDataParent !== null){ //generate ya map block deliveryFromMoscowYandexMap(); const moscowPickUpBlock = document.querySelector('.cart-delivery__moscow-pickup-wrapper'); const primaryDataTitle = document.querySelector('.cart-delivery-primary-data__title'); const primaryDataInputs = document.querySelector('.cart-delivery-primary-data__input'); if(deliveryTabs[0]){ if(deliveryTabs[0].checked){ // console.warn('tab1 chcked!'); moscowPickUpBlock.style.display = 'block'; primaryDataParent.style.display = 'none'; primaryDataTitle.style.display = 'none'; }else if(deliveryTabs[1].checked){ // console.warn('tab2 chcked!'); moscowPickUpBlock.style.display = 'none'; primaryDataParent.style.display = 'block'; primaryDataTitle.style.display = 'none'; primaryDataInputs.style.display = 'none'; }else if(deliveryTabs[2].checked){ // console.warn('tab3 chcked!'); moscowPickUpBlock.style.display = 'none'; primaryDataParent.style.display = 'block'; primaryDataTitle.style.display = 'block'; primaryDataInputs.style.display = 'flex'; }else if(deliveryTabs[3].checked){ // console.warn('tab3 chcked!'); moscowPickUpBlock.style.display = 'none'; primaryDataParent.style.display = 'block'; primaryDataTitle.style.display = 'block'; primaryDataInputs.style.display = 'flex'; }else{ setTimeout(() =>deliveryTabs[0].click(), 230); } deliveryTabs[0].addEventListener('click', function(){ // console.warn('tab1 CLICK!'); moscowPickUpBlock.style.display = 'block'; primaryDataParent.style.display = 'none'; primaryDataTitle.style.display = 'none'; primaryDataInputs.style.display = 'none'; }); deliveryTabs[1].addEventListener('click', function(){ // console.warn('tab2 CLICK!'); moscowPickUpBlock.style.display = 'none'; primaryDataParent.style.display = 'block'; primaryDataTitle.style.display = 'block'; primaryDataInputs.style.display = 'none'; }); deliveryTabs[2].addEventListener('click', function(){ // console.warn('tab3 CLICK!'); moscowPickUpBlock.style.display = 'none'; primaryDataParent.style.display = 'block'; primaryDataTitle.style.display = 'block'; primaryDataInputs.style.display = 'flex'; }); deliveryTabs[3].addEventListener('click', function(){ // console.warn('tab3 CLICK!'); moscowPickUpBlock.style.display = 'none'; primaryDataParent.style.display = 'block'; primaryDataTitle.style.display = 'block'; primaryDataInputs.style.display = 'flex'; }); } } } deliveryTabsMech(); //from Back-end || formSubmit function cartFormSubmit(formName, link) { event.preventDefault(); let form = ''; if (formName !== '') { form = document.forms[formName]; } else { form = document.forms[link.getAttribute("data-form")]; } if (link !== undefined) { form.setAttribute("action", link.getAttribute("href")); } form.submit(); } function submitFormSwitchForDeliverySection(){ const deliveryTabRadio = document.querySelectorAll(".cart-delivery__tab-input"); const headerCartNavItem = document.querySelectorAll(".header-cart-desktop .header-cart-desktop__nav-item a"); if(deliveryTabRadio === null){ // console.log('it`s not cart page!'); } else { for(let i = 0;i < deliveryTabRadio.length; i++) { if(deliveryTabRadio[i].type=="radio") { deliveryTabRadio[i].onchange=function() { var formId = this.getAttribute("id").replace(/[^0-9]/g,''); headerCartNavItem.forEach( function(x){ x.setAttribute("data-form", 'shop_order_form_1'); } ) } } } } } submitFormSwitchForDeliverySection(); //cart-confirmation disabled button function cartConfirmationDisabledBtn(){ const nextBtnDisabled = document.querySelectorAll('.cart-confirmation-send-order-btn--disabled'); if(nextBtnDisabled === null){ }else{ for(let i = 0;i < nextBtnDisabled.length; i++){ nextBtnDisabled[i].addEventListener('click', function(e){ e.preventDefault(); }); const disabledNextBtnTip = nextBtnDisabled[i].querySelector('.cart-confirmation-send-order-btn--disabled-tip') if(disabledNextBtnTip === null){ }else{ nextBtnDisabled[i].addEventListener('mouseover', function(e){ disabledNextBtnTip.style.opacity = '1'; disabledNextBtnTip.style.visibility = 'visible'; }); nextBtnDisabled[i].addEventListener('mouseout', function(e){ disabledNextBtnTip.style.opacity = '0'; disabledNextBtnTip.style.visibility = 'hidden'; }); } } } } cartConfirmationDisabledBtn() function cartPaymentNextBtnTrick(){ const btnInner = document.querySelectorAll('.cart-payment-next-step-btn__inner'); if(btnInner !== null){ let intViewportWidth = window.innerWidth; if(intViewportWidth > 1140){ btnInner.forEach(item => { const nextBtn = item.querySelector('.cart-payment-next-step-btn'); const paymentDetailsBlock = item.querySelector('.cart-customer-payment-details-data__inner'); if(paymentDetailsBlock){ }else{ nextBtn.classList.add('cart-payment-next-step-btn--nopaymentDetails'); } }); } } } cartPaymentNextBtnTrick(); //cart customer autoscroll function cartCustomerYurAutoScroll(){ const customerParent = document.querySelector('.cart-customer'); const customerTabs = document.querySelector('.cart-customer__tabs'); const customerTab2 = document.querySelector('#cart-customer-tab-2'); const customerTab1 = document.querySelector('#cart-customer-tab-1'); const customerRadioBtn1 = document.querySelector('#cart-customer-radio-btn-1'); if(customerTabs){ customerTab2.addEventListener('click', function(){ console.warn('CLICK'); let intViewportWidth = window.innerWidth; if(intViewportWidth < 1140){ const yOffset = -20; const y = customerTabs.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); customerRadioBtn1.click(); }else{ const yOffset = -90; const y = customerTabs.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); customerRadioBtn1.click(); } }); customerTab1.addEventListener('click', function(){ let intViewportWidth = window.innerWidth; if(intViewportWidth < 1140){ const yOffset = -20; const y = customerParent.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); }else{ const yOffset = -90; const y = customerParent.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); } }); } } cartCustomerYurAutoScroll() //REMOVE BEFORE RELEASE TESTING PORPOSE ONLY!!! maybe something can live in real live //Imitation of click on available method of paying in cart/payment //clear chosen variations after changing payment tab function refreshChoosenPaymentMathod(){ let paymentTab = document.querySelectorAll('.cart-payment__tab-label'); if(paymentTab){ function clearChosenVariations(){ let greenConfrimBlock = document.querySelectorAll('.cart-payment__option-info-wrapper'); let paymentRadio = document.querySelectorAll(".cart-payment__select-btn-radio"); if(greenConfrimBlock){ greenConfrimBlock.forEach(item => { item.classList.remove('cart-payment__option-info-wrapper--active'); }); paymentRadio.forEach(item => { item.checked=false; item.removeAttribute("checked"); }); } } paymentTab.forEach(item =>{ item.addEventListener('click', function(){ clearChosenVariations(); }); }); } } refreshChoosenPaymentMathod(); //from back | service refuse function cartServiceRefuseBtn() { let refuseBtn = document.querySelector('.service-refuse'); let confBox = document.querySelector('.cart-confirmation__conf-box'); let inputService = document.getElementById('shoporder-is_need_installation'); let infoBlock = document.querySelector('.cart-confirmation__service-inner'); if (confBox !== null) { let confBoxYes = confBox.querySelector('.conf-box__yes'); let confBoxNo = confBox.querySelector('.conf-box__no'); if (confBoxYes !== null || confBoxNo !== null) { confBoxYes.addEventListener('click', (event) => { inputService.value = 0; infoBlock.style.display = "none"; }); confBoxNo.addEventListener('click', (event) => { confBox.style.display = "none"; }); } } if (refuseBtn !== null) { refuseBtn.addEventListener('click', (event) => { event.preventDefault(); confBox.style.display = "flex"; }); } } cartServiceRefuseBtn(); function offerCardMobileInfoOpen(){ let mobileListItem = document.querySelectorAll('.mobile-list-item'); if (mobileListItem === null) { // console.log("mobileListItem left HTML"); } else { for(let i = 0; i < mobileListItem.length; i++){ let mobileProp = mobileListItem[i].querySelector(".mobile-properties"); let mobileInfoBlock = mobileListItem[i].querySelector(".mobile-info"); let mobileInfoBlockClose = mobileListItem[i].querySelector(".mobile-info__items-close"); if (mobileProp) { mobileProp.addEventListener("click", function(){ mobileInfoBlock.classList.toggle("mobile-info--on"); }); if(mobileInfoBlockClose){ mobileInfoBlockClose.addEventListener("click", function() { mobileInfoBlock.classList.remove("mobile-info--on"); }); } } } } } offerCardMobileInfoOpen(); function offerCardMobileOpen() { let offerCardMobile = document.querySelectorAll(".offer-card-mobile"); if (offerCardMobile === null) { // console.log("offerCardMobile left HTML"); } else { for(let i = 0; i < offerCardMobile.length; i++){ let offerCardMobileOpenBtn = offerCardMobile[i].querySelector(".short-panel-mobile__open"); let fullMobileCard = offerCardMobile[i].querySelector(".full-mobile-card"); let fullMobileCardVendorCodeForFocus = offerCardMobile[i].querySelector(".short-mobile-card__vendor-code"); let fullMobileCardCloseBtn = offerCardMobile[i].querySelector(".mobile-filter__close"); let shortOptionBlockMobile = offerCardMobile[i].querySelector(".short-options-mobile"); if (offerCardMobileOpenBtn === null || fullMobileCard === null || fullMobileCardCloseBtn === null || shortOptionBlockMobile === null) { // console.log("offerCard components left html"); } else { offerCardMobileOpenBtn.addEventListener("click", function() { fullMobileCard.classList.add("full-mobile-card--on"); offerCardMobileOpenBtn.style.visibility = 'hidden'; fullMobileCardVendorCodeForFocus.scrollIntoView({behavior: "smooth"}); }); fullMobileCardCloseBtn.addEventListener("click", function() { offerCardMobileOpenBtn.style.visibility = 'visible'; fullMobileCard.classList.remove("full-mobile-card--on"); shortOptionBlockMobile.scrollIntoView({behavior: "smooth"}); }); setTimeout(offerCardMobileMoreLink, 200); } } } } offerCardMobileOpen(); function offerCardMobileMoreLink(){ let mobileCards = document.querySelectorAll('.short-mobile-card'); if(mobileCards !== null){ mobileCards.forEach(item => { const vendorCode = item.querySelector('.short-mobile-card__vendor-code'); const vendorCodeHref = vendorCode.href; const mobileText = item.querySelector('.short-mobile-card__text'); const mobileMore = item.querySelector('.short-mobile-card__more'); if(mobileMore){ mobileMore.remove(); const link = document.createElement('a'); link.classList.add('short-mobile-card__more'); link.href = vendorCodeHref; link.textContent = 'Подробнее'; mobileText.appendChild(link); } }); } } //benner error on Desktop function errorBannerDesktop(){ let body = document.querySelector('body'); let oldErrorBanner = document.querySelector('.offers-catalog__error-banner-desktop'); if(oldErrorBanner){ oldErrorBanner.remove(); } let errorBanner = document.createElement('div'); errorBanner.classList.add('offers-catalog__error-banner-desktop'); errorBanner.innerText = 'Упс! Что-то пошло не так, попробуйте позже!'; body.appendChild(errorBanner); function errorBannerAppear(){ errorBanner.style.bottom = '35px'; } setTimeout(errorBannerAppear, 200); function errorBannerDisappear(){ errorBanner.style.left = '-700px'; } setTimeout(errorBannerDisappear, 7000); } //benner error on Mobile function errorBannerMobile(){ let body = document.querySelector('body'); let oldErrorBannerMobile = document.querySelector('.offers-catalog__error-banner-mobile'); if(oldErrorBannerMobile){ oldErrorBannerMobile.remove(); } let errorBanner = document.createElement('div'); errorBanner.classList.add('offers-catalog__error-banner-mobile'); errorBanner.innerText = 'Упс! Что-то пошло не так, попробуйте позже!'; body.appendChild(errorBanner); function errorBannerAppear(){ errorBanner.style.top = '0'; } setTimeout(errorBannerAppear, 200); function errorBannerDisappear(){ errorBanner.style.top = '-150px'; } setTimeout(errorBannerDisappear, 7000); } function errorBannerDesktopRemove(){ let errorBannerDesktop = document.querySelector('.offers-catalog__error-banner-desktop'); if(errorBannerDesktop === null){ }else{ errorBannerDesktop.remove(); } } function errorBannerMobileRemove(){ let errorBannerMobile = document.querySelector('.offers-catalog__error-banner-mobile'); if(errorBannerMobile === null){ }else{ errorBannerMobile.remove(); } } //favorite button tooltip mechanic function mobileFavoriteTooltip(){ let favoriteTooltip = document.createElement('div'); let body = document.querySelector('body'); favoriteTooltip.classList.add('mobile-buy__favorite-btn-tooltip') favoriteTooltip.innerHTML = ` <a href="/favorite"> <div class="mobile-buy__favorite-btn-tooltip-wrapper"> Товар успешно добавлен в избранное. Нажмите, чтобы перейти </div> </a> ` body.appendChild(favoriteTooltip); function mobileFavoriteTooltipSmoothAppearance(){ favoriteTooltip.style.top = '-3px'; } function mobileFavoriteTooltipCloseToTimer(){ favoriteTooltip.style.top = '-150px'; } window.addEventListener('scroll', function(e){ let scrollPos = window.scrollY; // console.log(scrollPos); if (scrollPos < 200) { favoriteTooltip.style.top = '-150px'; } }); setTimeout(mobileFavoriteTooltipSmoothAppearance, 300) setTimeout(mobileFavoriteTooltipCloseToTimer, 7000) } // Remove favorite button mechanic on Mobile function mobileFavoriteTooltipRemove(){ let favoriteTooltip = document.createElement('div'); let body = document.querySelector('body'); favoriteTooltip.classList.add('mobile-buy__favorite-btn-tooltip') favoriteTooltip.innerHTML = ` <a href="/favorite"> <div class="mobile-buy__favorite-btn-tooltip-wrapper"> Товар удален из избранного </div> </a> ` favoriteTooltip.style.height = '60px'; body.appendChild(favoriteTooltip); function mobileFavoriteTooltipSmoothAppearance(){ favoriteTooltip.style.top = '-3px'; } function mobileFavoriteTooltipCloseToTimer(){ favoriteTooltip.style.top = '-150px'; } window.addEventListener('scroll', function(e){ let scrollPos = window.scrollY; // console.log(scrollPos); if (scrollPos < 200) { favoriteTooltip.style.top = '-150px'; } }); setTimeout(mobileFavoriteTooltipSmoothAppearance, 300) setTimeout(mobileFavoriteTooltipCloseToTimer, 7000) } //favorite button mechanic on Mobile ✰2 function offerCardFavoriteBtnMobileAdd() { let shortOptionsMobile = document.querySelectorAll('.short-options-mobile'); let mobileHeaderFavoriteCounter = document.querySelector('.user-mobile__favorites span'); if (shortOptionsMobile === null) { // console.log('no offers on page'); } else{ for(let i = 0; i < shortOptionsMobile.length; i++){ let currentFavBtn = shortOptionsMobile[i].querySelector('.short-options-mobile__favorite'); let currentFavBtnActive = shortOptionsMobile[i].querySelector('.short-options-mobile__favorite-active'); let favBtnKey = currentFavBtn.dataset.key; currentFavBtn.addEventListener('click', function(){ offerCardFavoriteTooltipRemover(); function sendFavBtnKeyToSeverOnMobile() { let xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/add'); xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded"); xhr.onload = () => { if (xhr.status === 200) { const jsonResponse = JSON.parse(xhr.responseText);; let countFavFromServer = ++jsonResponse.count; // console.warn(countFromFav) mobileHeaderFavoriteCounter.innerText = countFavFromServer; currentFavBtnActive.style.display = 'block'; mobileFavoriteTooltip(); stickyHeaderMobileFavCountUpdate(); trackFavoriteCountMobile(); }else { console.warn('favoriteMobileMech ajax error'); errorBannerMobileRemove(); errorBannerMobile(); } } xhr.send('key=' + favBtnKey); } setTimeout(function(){ sendFavBtnKeyToSeverOnMobile(); }, 200); }); } } } offerCardFavoriteBtnMobileAdd(); function offerCardFavoriteBtnMobileRemove() { let shortOptionsMobile = document.querySelectorAll('.short-options-mobile'); let mobileHeaderFavoriteCounter = document.querySelector('.user-mobile__favorites span'); if (shortOptionsMobile === null) { // console.log('no offers on page'); } else{ for(let i = 0; i < shortOptionsMobile.length; i++){ let currentFavBtn = shortOptionsMobile[i].querySelector('.short-options-mobile__favorite'); let currentFavBtnActive = shortOptionsMobile[i].querySelector('.short-options-mobile__favorite-active'); let activeFavBtnKey = currentFavBtnActive.dataset.key; currentFavBtnActive.addEventListener('click', function(){ offerCardFavoriteTooltipRemover(); function sendFavBtnKeyToSeverOnMobileRemove(){ let xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/remove'); xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded"); xhr.onload = () => { if (xhr.status === 200) { // currentPreloader.style.display = 'none'; const jsonResponse = JSON.parse(xhr.responseText);; let countFavFromServer = --jsonResponse.count; // console.warn(countFromFav) mobileHeaderFavoriteCounter.innerText = countFavFromServer; mobileFavoriteTooltipRemove(); stickyHeaderMobileFavCountUpdate(); trackFavoriteCountMobile(); currentFavBtnActive.style.display = 'none'; }else { console.warn('favoriteMobileMech ajax error'); errorBannerMobileRemove(); errorBannerMobile(); } } xhr.send('key=' + activeFavBtnKey); } setTimeout(function(){ sendFavBtnKeyToSeverOnMobileRemove(); }, 200); }); } } } offerCardFavoriteBtnMobileRemove(); //tooltip remover function offerCardFavoriteTooltipRemover(){ let tooltips = document.querySelectorAll('.mobile-buy__favorite-btn-tooltip'); if(tooltips === null){ }else{ tooltips.forEach(item => { item.remove(); }) } } //favorite button mechanic on Desktop ✰1 function offersCardDesktopFavoriteBtnAdd() { let shortOptionsDesktop = document.querySelectorAll('.short-options-desktop'); let body = document.querySelector('.page-body'); let mainHeaderFavoriteCounter = document.querySelector('.user__favorites span'); if (shortOptionsDesktop === null) { // console.log('favBtn left HTML'); } else { for(let i = 0; i < shortOptionsDesktop.length; i++) { let curentFavBtn = shortOptionsDesktop[i].querySelector('.short-options-desktop__favorite'); let curentFavBtnActive = shortOptionsDesktop[i].querySelector('.short-options-desktop__favorite-active'); let currentTooltip = shortOptionsDesktop[i].querySelector('.short-options-desktop__favorite-tooltip'); // let currentTooltipIcon = shortOptionsDesktop[i].querySelector('.short-options-desktop__favorite-tooltip-icon'); let currentTooltipText = shortOptionsDesktop[i].querySelector('.short-options-desktop__favorite-tooltip-text'); let currentOffer = shortOptionsDesktop[i].parentElement; let imageOfCurrentOffer = currentOffer.querySelector('.short-desktop-card__picture'); let titleOfCurrentOffer = currentOffer.querySelector('.short-card-description__title'); curentFavBtn.addEventListener('mouseover', function(){ currentTooltip.style.display = 'flex'; }); curentFavBtn.addEventListener('mouseout', function(){ currentTooltip.style.display = 'none'; }); let favBtnKey = curentFavBtn.dataset.key; curentFavBtn.addEventListener('click', function(){ favBannerDesktopClear(); currentTooltip.style.display = 'flex'; // currentTooltipIcon.classList.add('short-options-desktop__favorite-tooltip-icon--load'); currentTooltipText.innerHTML = `Добавляем . . .`; function sendFavBtnKeyToServer() { const xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/add'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // currentTooltipIcon.classList.remove('short-options-desktop__favorite-tooltip-icon--load'); curentFavBtnActive.classList.add('short-options-desktop__favorite-active--on'); let favBanner = document.createElement("div"); favBanner.classList.add('favorite-banner'); body.appendChild(favBanner); let imgForFavBtn = imageOfCurrentOffer.innerHTML; let titleForFavBtn = titleOfCurrentOffer.innerHTML; //dynamic data from cart const jsonResponse = JSON.parse(xhr.responseText); let countFromFav = ++jsonResponse.count; // console.warn(countFromFav) mainHeaderFavoriteCounter.innerText = countFromFav; // Вариативное окончание товара function endingGenerate(int, array) { return (array = array || ['товар', 'товара', 'товаров']) && array[(int % 100 > 4 && int % 100 < 20) ? 2 : [2, 0, 1, 1, 1, 2][(int % 10 < 5) ? int % 10 : 5]]; } const endingGenerated = endingGenerate(countFromFav); favBanner.innerHTML = ` <div class="favorite-banner__inner"> <div class="favorite-banner__picture"> ${imgForFavBtn} </div> <div class="favorite-banner__info-wrapper"> <div class="favorite-banner__product-title"> ${titleForFavBtn} </div> <div class="favorite-banner__info-text"> Добавлен в Избранное </div> <div class="favorite-banner__list-info"> в списке ${countFromFav} ${endingGenerated} </div> </div> <div class="favorite-banner__action"> <div class="favorite-banner__btn"> <a href="/favorite">Перейти в Избранное</a> </div> <div class="favorite-banner__close"></div> </div> </div> `; let favBtnClose = document.querySelector('.favorite-banner__close'); favBtnClose.addEventListener('click', function(){ favBanner.remove(); }); // window.addEventListener('scroll', function(e){ // let scrollPos = window.scrollY; // if (scrollPos < 600) { // favBannerDesktopClear(); // } // }); function favBannerSmoothAppearenceOn(){ favBanner.style.top = '0'; } function favBannerSmoothAppearenceOff(){ favBanner.style.top = '-150px'; } stickyHeaderDesktopFavoriteCountUpdate(); trackFavoriteCount(); setTimeout(favBannerSmoothAppearenceOn, 300); // setTimeout(favBannerSmoothAppearenceOff, 30000); //close blocks on document cliks function handleClick(event) { const target = event.target; const isClickedOnExcludedBlock = target.matches('.favorite-banner__btn a, .favorite-banner__picture, .favorite-banner__info-wrapper'); if (!isClickedOnExcludedBlock) { // Handle the click event here for clicks outside the excluded blocks favBannerSmoothAppearenceOff(); } } document.addEventListener('click', handleClick); }else if(this.readyState != 4 && this.status != 200){ errorBannerDesktopRemove(); errorBannerDesktop(); currentTooltip.style.visibility = 'hidden'; } } xhr.send('key=' + favBtnKey); } sendFavBtnKeyToServer(); }); } } } offersCardDesktopFavoriteBtnAdd(); function offersCardDesktopFavoriteBtnRemove() { let shortOptionsDesktop = document.querySelectorAll('.short-options-desktop'); let body = document.querySelector('.page-body'); let mainHeaderFavoriteCounter = document.querySelector('.user__favorites span'); if (shortOptionsDesktop === null) { // console.log('favBtn left HTML'); } else { for(let i = 0; i < shortOptionsDesktop.length; i++) { let curentFavBtn = shortOptionsDesktop[i].querySelector('.short-options-desktop__favorite'); let curentFavBtnActive = shortOptionsDesktop[i].querySelector('.short-options-desktop__favorite-active'); let currentTooltip = shortOptionsDesktop[i].querySelector('.short-options-desktop__favorite-tooltip'); // let currentTooltipIcon = shortOptionsDesktop[i].querySelector('.short-options-desktop__favorite-tooltip-icon'); let currentTooltipText = shortOptionsDesktop[i].querySelector('.short-options-desktop__favorite-tooltip-text'); let currentOffer = shortOptionsDesktop[i].parentElement; let imageOfCurrentOffer = currentOffer.querySelector('.short-desktop-card__picture'); let titleOfCurrentOffer = currentOffer.querySelector('.short-card-description__title'); curentFavBtnActive.addEventListener('mouseover', function(){ currentTooltip.style.display = 'flex'; currentTooltipText.innerHTML = `Удалить из Избранного`; }); curentFavBtnActive.addEventListener('mouseout', function(){ currentTooltip.style.display = 'none'; }); let favBtnActiveKey = curentFavBtnActive.dataset.key; curentFavBtnActive.addEventListener('click', function(){ favBannerDesktopClear(); currentTooltip.style.display = 'flex'; // currentTooltipIcon.classList.add('short-options-desktop__favorite-tooltip-icon--load'); currentTooltipText.innerHTML = `Удаляем . . .`; function sendFavBtnKeyToServerRemove() { let xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/remove'); xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded"); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // currentTooltipIcon.classList.remove('short-options-desktop__favorite-tooltip-icon--load'); curentFavBtnActive.classList.remove('short-options-desktop__favorite-active--on'); currentTooltipText.innerHTML = `Добавить в Избранное`; let favBanner = document.createElement("div"); favBanner.classList.add('favorite-banner'); body.appendChild(favBanner); let imgForFavBtn = imageOfCurrentOffer.innerHTML; let titleForFavBtn = titleOfCurrentOffer.innerHTML; const jsonResponse = JSON.parse(xhr.responseText);; let countFromFav = --jsonResponse.count; mainHeaderFavoriteCounter.innerText = countFromFav; // Вариативное окончание товара function endingGenerate(int, array) { return (array = array || ['товар', 'товара', 'товаров']) && array[(int % 100 > 4 && int % 100 < 20) ? 2 : [2, 0, 1, 1, 1, 2][(int % 10 < 5) ? int % 10 : 5]]; } const endingGenerated = endingGenerate(countFromFav); favBanner.innerHTML = ` <div class="favorite-banner__inner"> <div class="favorite-banner__picture"> ${imgForFavBtn} </div> <div class="favorite-banner__info-wrapper"> <div class="favorite-banner__product-title"> ${titleForFavBtn} удален из избранного </div> <div class="favorite-banner__info-text"> </div> <div class="favorite-banner__list-info"> в списке ${countFromFav} ${endingGenerated} </div> </div> <div class="favorite-banner__action"> <div class="favorite-banner__btn" style="opacity: 0; pointer-events: none;"> <a href="">Перейти в Избранное</a> </div> <div class="favorite-banner__close"></div> </div> </div> `; let favBtnClose = document.querySelector('.favorite-banner__close'); favBtnClose.addEventListener('click', function(){ favBanner.remove(); }); // window.addEventListener('scroll', function(e){ // let scrollPos = window.scrollY; // if (scrollPos < 600) { // favBannerDesktopClear(); // } // }); function favBannerSmoothAppearenceOn(){ favBanner.style.top = '0'; } function favBannerSmoothAppearenceOff(){ favBanner.style.top = '-150px'; } setTimeout(favBannerSmoothAppearenceOn, 300); // setTimeout(favBannerSmoothAppearenceOff, 10000); function handleClick(event) { const target = event.target; const isClickedOnExcludedBlock = target.matches('.favorite-banner__btn a, .favorite-banner__picture, .favorite-banner__info-wrapper'); if (!isClickedOnExcludedBlock) { // Handle the click event here for clicks outside the excluded blocks favBannerSmoothAppearenceOff(); } } document.addEventListener('click', handleClick); stickyHeaderDesktopFavoriteCountUpdate(); trackFavoriteCount(); }else{ currentTooltipText.innerHTML = `Что-то пошло не так . . .`; } } xhr.send('key=' + favBtnActiveKey); } sendFavBtnKeyToServerRemove(); }); } } } offersCardDesktopFavoriteBtnRemove(); //btns tips in special-offers on index page function specialOfferFavBtnTooltip(){ let favBtnsDefaultList = document.querySelectorAll('.special-offer-card__favorite--default'); let favBtnsActiveList = document.querySelectorAll('.special-offer-card__favorite--active'); if (favBtnsDefaultList === null){ // console.log('no special offers on the page'); }else{ let intViewportWidth = window.innerWidth; if(intViewportWidth > 1140){ for(let i = 0;i < favBtnsDefaultList.length; i++){ favBtnsDefaultList[i].addEventListener('mouseover', function(){ let currentTooltip = this.querySelector('.special-offer-card__favorite-default-tip'); currentTooltip.style.visibility = 'visible'; currentTooltip.style.opacity = '1'; }); favBtnsDefaultList[i].addEventListener('mouseout', function(){ let currentTooltip = this.querySelector('.special-offer-card__favorite-default-tip'); currentTooltip.style.visibility = 'hidden'; currentTooltip.style.opacity = '0'; }); } for(let i = 0; i < favBtnsActiveList.length; i++){ favBtnsActiveList[i].addEventListener('mouseover', function(){ let currentActiveTooltip = this.querySelector('.special-offer-card__favorite-active-tip'); currentActiveTooltip.style.visibility = 'visible'; currentActiveTooltip.style.opacity = '1'; }); favBtnsActiveList[i].addEventListener('mouseout', function(){ let currentActiveTooltip = this.querySelector('.special-offer-card__favorite-active-tip'); currentActiveTooltip.style.visibility = 'hidden'; currentActiveTooltip.style.opacity = '0'; }); } } } } specialOfferFavBtnTooltip(); //Favorite button mech for Special Offers On mainPage *in slider function specialOfferFavoriteMech(){ let favBtnsDefaultList = document.querySelectorAll('.special-offer-card__favorite--default'); let favBtnsActiveList = document.querySelectorAll('.special-offer-card__favorite--active'); let mainHeaderFavoriteCounter = document.querySelector('.user__favorites span'); if (favBtnsDefaultList === null){ // console.log('no special offers on the page'); } else{ for(let i = 0;i < favBtnsDefaultList.length; i++){ favBtnsDefaultList[i].addEventListener('click', function(e){ let currentFavBtn = this; let currentActiveBtn = currentFavBtn.nextElementSibling; let favBtnKey = currentFavBtn.dataset.key; function sendSpecFavBtnKeyToServer() { const xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/add'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // currentTooltipIcon.classList.remove('short-options-desktop__favorite-tooltip-icon--load'); currentActiveBtn.classList.add('special-offer-card__favorite--active-on'); //dynamic data from cart const jsonResponse = JSON.parse(xhr.responseText); let countFromFav = ++jsonResponse.count; mainHeaderFavoriteCounter.innerText = countFromFav; stickyHeaderDesktopFavoriteCountUpdate(); }else if(this.readyState != 4 && this.status != 200){ errorBannerDesktopRemove(); errorBannerDesktop(); currentTooltip.style.visibility = 'hidden'; } } xhr.send('key=' + favBtnKey); } sendSpecFavBtnKeyToServer(); }); } for(let i = 0; i < favBtnsActiveList.length; i++){ favBtnsActiveList[i].addEventListener('click', function(e){ let currentActiveFavBtn = this; let favBtnKey = currentActiveFavBtn.dataset.key; function sendSpecFavBtnKeyToServer() { const xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/remove'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // currentTooltipIcon.classList.remove('short-options-desktop__favorite-tooltip-icon--load'); currentActiveFavBtn.classList.remove('special-offer-card__favorite--active-on'); //dynamic data from cart const jsonResponse = JSON.parse(xhr.responseText); let countFromFav = --jsonResponse.count; mainHeaderFavoriteCounter.innerText = countFromFav; stickyHeaderDesktopFavoriteCountUpdate(); }else if(this.readyState != 4 && this.status != 200){ errorBannerDesktopRemove(); errorBannerDesktop(); currentTooltip.style.visibility = 'hidden'; } } xhr.send('key=' + favBtnKey); } sendSpecFavBtnKeyToServer(); }); } } } //Favorite button mech for Special Offers in Catalog function specialOfferFavoriteMechCatalog(){ let favBtnsDefaultList = document.querySelectorAll('.special-offer-catalog__card-favorite--default'); let favBtnsActiveList = document.querySelectorAll('.special-offer-catalog__card-favorite--active'); let mainHeaderFavoriteCounter = document.querySelector('.user__favorites span'); if (favBtnsDefaultList === null){ // console.log('no special offers on the page'); } else{ for(let i = 0;i < favBtnsDefaultList.length; i++){ favBtnsDefaultList[i].addEventListener('click', function(e){ let currentFavBtn = this; let currentActiveBtn = currentFavBtn.nextElementSibling; let favBtnKey = currentFavBtn.dataset.key; function sendSpecFavBtnKeyToServer() { const xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/add'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // currentTooltipIcon.classList.remove('short-options-desktop__favorite-tooltip-icon--load'); currentActiveBtn.classList.add('special-offer-catalog__card-favorite--active-on'); //dynamic data from cart const jsonResponse = JSON.parse(xhr.responseText); let countFromFav = ++jsonResponse.count; mainHeaderFavoriteCounter.innerText = countFromFav; stickyHeaderDesktopFavoriteCountUpdate(); }else if(this.readyState != 4 && this.status != 200){ errorBannerDesktopRemove(); errorBannerDesktop(); currentTooltip.style.visibility = 'hidden'; } } xhr.send('key=' + favBtnKey); } sendSpecFavBtnKeyToServer(); }); } for(let i = 0; i < favBtnsActiveList.length; i++){ favBtnsActiveList[i].addEventListener('click', function(e){ let currentActiveFavBtn = this; let favBtnKey = currentActiveFavBtn.dataset.key; function sendSpecFavBtnKeyToServer() { const xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/remove'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { // currentTooltipIcon.classList.remove('short-options-desktop__favorite-tooltip-icon--load'); currentActiveFavBtn.classList.remove('special-offer-catalog__card-favorite--active-on'); //dynamic data from cart const jsonResponse = JSON.parse(xhr.responseText); let countFromFav = --jsonResponse.count; mainHeaderFavoriteCounter.innerText = countFromFav; stickyHeaderDesktopFavoriteCountUpdate(); }else if(this.readyState != 4 && this.status != 200){ errorBannerDesktopRemove(); errorBannerDesktop(); currentTooltip.style.visibility = 'hidden'; } } xhr.send('key=' + favBtnKey); } sendSpecFavBtnKeyToServer(); }); } } } //Clear prev favorite banner function favBannerDesktopClear(){ let favBannerDesktop = document.querySelector('.favorite-banner'); if(favBannerDesktop === null){ }else { favBannerDesktop.remove(); } } //cart with no offers dynamic border function offersDesktopNoOfferBorder(){ const offersCards = document.querySelectorAll('.offer-card-desktop'); if(offersCards !== null){ offersCards.forEach(item => { const noOfferBlock = item.querySelector('.short-options-desktop__no-offers'); const shortDesktopCard = item.querySelector('.short-desktop-card'); if(noOfferBlock){ shortDesktopCard.style.borderBottom = '3px solid #f4f6fc'; shortDesktopCard.style.borderRadius = '7px 7px 7px 7px'; } }); } } offersDesktopNoOfferBorder(); //MODAL BUY DESKTOP✰ //Modal storage switcher function offerCardDesktopBuyModalLocalStorageSwitcher(){ let modalPar = localStorage.getItem('modalPar'); if(modalPar === null){ // console.warn('modalParametr are not exist yet! Creating one right one. . .'); localStorage.setItem('modalPar', 'modalBuy'); }else if(modalPar === "modalBuy"){ // console.warn('localStorage ModalPar switcher ON'); }else if(modalPar === "noModal"){ // console.warn('localStorage ModalPar switcher OFF'); } } //Hiden localStorage clear mech for ninja function offerCardDesktopBuyModalLocalStorageSwitcherClear(){ let stocksItem = document.querySelectorAll('.short-options-desktop__stock'); if(stocksItem === null){ }else{ // console.warn('localStorage cleaner activate just now! 🤖'); stocksItem.forEach(item => { item.addEventListener("dblclick", function(){ localStorage.clear(); document.location.reload(); // console.warn('localStorage clean for sure! 🤖'); }) }) } } //Modal localStorageHideMech function offerCardDesktopBuyModalLocalStorageSwitcherHide(){ let modalHideInputBlock = document.querySelector('.buy-offer-modal-desktop__hide-input'); let body = document.querySelector('body'); if(modalHideInputBlock === null){ }else{ let modalHideInputCkeckBox = modalHideInputBlock.querySelector('label'); if(modalHideInputCkeckBox === null){ }else{ modalHideInputCkeckBox.addEventListener('click', function(){ localStorage.setItem('modalPar', 'noModal'); let modalBlockParent = document.querySelector('.buy-offer-modal-desktop'); let modalBlock = document.querySelector('.buy-offer-modal-desktop__wrapper'); function modalBlockDisapear1(){ modalBlock.style.left = '53%'; } function modalBlockDisapear2(){ modalBlock.style.left = '-120%'; } function parentDisapear(){ modalBlockParent.style.visibility = 'hidden'; modalBlockParent.style.display = 'none'; } function blockRemove(){ modalBlockParent.remove() } setTimeout(modalBlockDisapear1, 500); setTimeout(modalBlockDisapear2, 800); setTimeout(parentDisapear, 900); setTimeout(function(){ document.location.reload(); }, 950) }) } } } //Add to cart button Desktop ✰3 function offerCardDesktopBuyButtonMech() { let offersAcrticle = document.querySelectorAll('article.offer-card-desktop'); let body = document.querySelector('body'); let cartBtnDesktopMainHeaderSpan = document.querySelector('.user__shopping-cart span'); if(offersAcrticle === null){ }else { // debugger; offerCardDesktopBuyModalLocalStorageSwitcherClear(); offerCardDesktopBuyModalLocalStorageSwitcher(); for(let i = 0; i < offersAcrticle.length; i++){ let offerPictureLink = offersAcrticle[i].querySelector('.short-desktop-card__picture'); let offerPicture = offerPictureLink.querySelector('a'); let offerVendorCode = offersAcrticle[i].querySelector('.short-card-description__vendor-code'); let offerTitle = offersAcrticle[i].querySelector('.short-card-description__title'); let offerFullCardItems = offersAcrticle[i].querySelectorAll('.full-desktop-card__item'); for(let i = 0; i < offerFullCardItems.length; i++){ let offerManufacturer = offerFullCardItems[i].querySelector('.desktop-properties__manufacturer'); let offerPrice = offerFullCardItems[i].querySelector('.desktop-card-item__price'); let offerbuyBtns = offerFullCardItems[i].querySelectorAll('.desktop-buy__buy-btn'); // debugger; if(offerbuyBtns === null){ // "buyBtns left HTML"; }else{ let modalPar = localStorage.getItem('modalPar'); if(modalPar === "modalBuy"){ for (let i = 0; i < offerbuyBtns.length; i++){ offerbuyBtns[i].addEventListener('click', function buyBtnFunc(e) { e.preventDefault(); //reset custom quantity value localStorage.setItem('customQuantityInputValue', ''); let thisBtn = this; thisBtn.classList.remove('desktop-buy__buy-btn'); thisBtn.classList.add('desktop-buy__buy-btn--load'); thisBtn.innerHTML = `<div class="desktop-buy__buy-btn-preloader"></div>`; let stickyHeaderDesktop = document.querySelector('.sticky-header-desktop'); stickyHeaderDesktop.style.top = '-150px'; // let key = encodeURIComponent(thisBtn.dataset.key); let key = thisBtn.dataset.key; let availability = thisBtn.dataset.availability; function sendOfferToCart() { const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardDesktopBuyButtonMech ajax error'); errorBannerDesktopRemove(); errorBannerDesktop(); thisBtn.classList.remove('desktop-buy__buy-btn--load'); thisBtn.classList.add('desktop-buy__buy-btn'); thisBtn.innerHTML = ` `; }else{ const response = xhr.response; let currentPreloader = thisBtn.querySelector('.desktop-buy__buy-btn-preloader'); currentPreloader.remove(); thisBtn.classList.remove('desktop-buy__buy-btn--load'); thisBtn.classList.add('desktop-buy__buy-btn'); thisBtn.innerHTML = ` `; //init parent + add tooltip let parentBuyBlockDesktop = thisBtn.parentElement; let currentFastBtn = parentBuyBlockDesktop.querySelector('.desktop-buy__fast-buy-btn'); let desktopCardItemInner = parentBuyBlockDesktop.parentElement; //Availability sign of offer let offerCardAvailableSign = desktopCardItemInner.querySelector('.desktop-description__shop'); //Hide buttons thisBtn.style.display = 'none'; if(currentFastBtn){ currentFastBtn.style.display = 'none'; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Add quantity btns instead buy btn let quantityParent = document.createElement('div'); quantityParent.classList.add('desktop-buy-quantity'); let quantityCustomParent = document.createElement('div'); quantityCustomParent.classList.add('desktop-buy-quantity--custom'); quantityParent.innerHTML = ` <div class="desktop-buy-quantity__btn-minus" data-key="${key}"></div> <input class="desktop-buy-quantity__default-input" placeholder="1"> <div class="desktop-buy-quantity__btn-plus" data-key="${key}"></div> `; quantityCustomParent.innerHTML = ` <div class="desktop-buy-quantity__back-btn"></div> <div class="desktop-buy-quantity__custom-input-wrapper"> <input class="desktop-buy-quantity__custom-input" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a class="desktop-buy-quantity__buy-btn"></a> </div> `; parentBuyBlockDesktop.appendChild(quantityParent); parentBuyBlockDesktop.appendChild(quantityCustomParent); const afterBuyMinusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-minus'); let afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyCustomInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyPlusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-plus'); const afterBuyQuantityBuyButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__buy-btn'); //Close offer-buy modal function offerCardDesktopBuyModalCloseMech(){ let modalBlockParent = document.querySelector('.buy-offer-modal-desktop'); let modalBlockCloseBtn = document.querySelector('.buy-offer-modal-desktop__close-btn'); let modalBlockStayBtn = document.querySelector('.buy-offer-modal-desktop-panel__stay-btn'); let body = document.querySelector('body'); let stickyHeaderDesktop = document.querySelector('.sticky-header-desktop'); if(modalBlockParent === null){ }else{ modalBlockCloseBtn.addEventListener('click', function(){ modalBlockParent.style.display = 'none'; body.classList.remove('page-body__no-scroll'); modalBlockParent.remove(); stickyHeaderDesktop.style.top = '0'; //reset custom quantity value localStorage.setItem('customQuantityInputValue', ''); checkAvailabilityBeforeClick(); }) modalBlockStayBtn.addEventListener('click', function(e){ e.preventDefault(); modalBlockParent.style.display = 'none'; body.classList.remove('page-body__no-scroll'); modalBlockParent.remove(); stickyHeaderDesktop.style.top = '0'; //reset custom quantity value localStorage.setItem('customQuantityInputValue', ''); checkAvailabilityBeforeClick(); }) } } //function for checking availability and hide plus-btn if it`s required function checkAvailabilityBeforeClick(){ let afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyInputPlaceholder = afterBuyInput.placeholder; if(Number(afterBuyInputPlaceholder) >= Number(availability)){ // console.warn('afterBuyInputPlaceholder >= availability'); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus--disable'); afterBuyInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClick(); //NO modal buy Mechanics!!! - Mechs in offer-desktop-card afterBuyMinusButton.addEventListener('click', function(){ //Mechanic after click on Minus button if(afterBuyInput.placeholder == '1'){ const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Quantity + - hidden quantityParent.remove(); quantityCustomParent.remove(); //Fast buy & buy btn onn currentFastBtn.style.display = 'block'; thisBtn.style.display = 'block'; } } xhr.send(params); }else{ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ // If 1 offer in afterBuyInputBlock checking const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); --afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus--disable'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus'); afterBuyInput.style.pointerEvents = 'auto'; } } xhr.send(params); } }); afterBuyPlusButton.addEventListener('click', function(){ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); ++afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; checkAvailabilityBeforeClick(); } } xhr.send(params); }); afterBuyInput.addEventListener('click', function(){ quantityParent.style.display = 'none'; quantityCustomParent.style.display = 'flex'; const afterBuyCustomQuantityInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyCustomQuantityBackBtn = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__back-btn'); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyInput.placeholder); afterBuyCustomQuantityInput.value = afterBuyInput.placeholder; afterBuyCustomQuantityInput.focus(); afterBuyCustomQuantityInput.addEventListener('input', function updateCustomInputValue(e){ const afterBuyCustomQuantityInputValue = afterBuyCustomQuantityInput.value; if(Number(afterBuyCustomQuantityInput.value) < Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); }else if(Number(afterBuyCustomQuantityInput.value) >= Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyCustomQuantityInput.value = availability; localStorage.setItem('noModalCustomQuantityInputValue', availability); }else if(typeof availability === 'string'){ localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); } }); afterBuyCustomQuantityBackBtn.addEventListener('click', function(){ quantityCustomParent.style.display = 'none'; quantityParent.style.display = 'flex'; }); }); afterBuyQuantityBuyButton.addEventListener('click', function(e){ e.preventDefault(); let noModalCustomQuantityInputValue = localStorage.getItem('noModalCustomQuantityInputValue'); if(noModalCustomQuantityInputValue == ''){ // console.warn('noModalCustomQuantityInputValue === empty string'); }else{ // console.warn('noModalCustomQuantityInputValue'); // console.warn(noModalCustomQuantityInputValue); let thisBtn = this; thisBtn.classList.remove('desktop-buy-quantity__buy-btn'); thisBtn.classList.add('desktop-buy-quantity__buy-btn--load'); thisBtn.innerHTML = `<div class="desktop-custom-quantity-buy__buy-btn-preloader"></div>`; function sendOfferToCartDesktopCustomQuamnity(){ const params = new URLSearchParams(); params.set('id', key); params.append('qty', noModalCustomQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('modalCustomQuantityBuyButtonMech ajax error'); } else { // console.warn('modalCustomQuantityBuyButtonMech ajax SUCCESS'); thisBtn.classList.remove('desktop-buy-quantity__buy-btn--load'); thisBtn.classList.add('desktop-buy-quantity__buy-btn'); thisBtn.innerHTML = ` `; // dynamic data from cart const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); afterBuyInput.placeholder = noModalCustomQuantityInputValue; quantityParent.style.display = 'flex'; quantityCustomParent.style.display = 'none'; checkAvailabilityBeforeClick(); } } xhr.send(params); } setTimeout(sendOfferToCartDesktopCustomQuamnity, 300); } }); //ModalBuy mech start here let picForModalsOffer = offerPicture.innerHTML; let vendorCodeForModalsOffer = offerVendorCode.innerHTML; let titleForModalsOffer = offerTitle.innerHTML; let manufacturerForModalsOffer = offerManufacturer.innerHTML; let priceForModalsOffer = offerPrice.innerHTML; //dynamic data from cart // let countFromCart = response.count; let totalFromCart = response.total; let stringTotalFromCart = totalFromCart.toString(); let reTotalFromCart = stringTotalFromCart.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); //Вариативное окончание "Товара" function endingGenerate(int, array) { return (array = array || ['товар', 'товара', 'товаров']) && array[(int % 100 > 4 && int % 100 < 20) ? 2 : [2, 0, 1, 1, 1, 2][(int % 10 < 5) ? int % 10 : 5]]; } const endingGenerated = endingGenerate(countFromCart); cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; trackCartCount(); let buyOfferModalDesktop = document.createElement("section"); buyOfferModalDesktop.classList.add('buy-offer-modal-desktop'); buyOfferModalDesktop.innerHTML = `<div class="buy-offer-modal-desktop__blur"></div> <div class="buy-offer-modal-desktop__wrapper"> <div class="buy-offer-modal-desktop__title-wrapper"> <div class="buy-offer-modal-desktop__title">Товар успешно добавлен в корзину</div> <div class="buy-offer-modal-desktop__close-btn"></div> </div> <div class="buy-offer-modal-desktop__panel-wrapper"> <!-- product --> <div class="buy-offer-modal-desktop__product buy-offer-modal-desktop-product"> <div class="buy-offer-modal-desktop-product__description"> <div class="buy-offer-modal-desktop-product__picture"> <a href="${offerPicture.href}" target="_blank"> ${picForModalsOffer} </a> </div> <div class="buy-offer-modal-desktop-product__description-inner"> <div class="buy-offer-modal-desktop-product__vendor-code">Артикул: <span>${vendorCodeForModalsOffer}</span></div> <a href="${offerPicture.href}" class="buy-offer-modal-desktop-product__title" target="_blank"> ${titleForModalsOffer} </a> <div class="buy-offer-modal-desktop-product__quality-wrapper"> <div class="buy-offer-modal-desktop-product__manufactor">${manufacturerForModalsOffer}</div> <div class="buy-offer-modal-desktop-product__quality" style="display:none">genuine</div> </div> </div> </div> <div class="buy-offer-modal-desktop-product__price-panel"> <div class="buy-offer-modal-desktop-product__price">Цена (шт):<span>${priceForModalsOffer}</span></div> <!-- default --> <div class="buy-offer-modal-desktop-product__quantity"> <div class="buy-offer-modal-desktop-product__alert" style="display: none;">oсталось: 12 шт</div> <div class="buy-offer-modal-desktop-product__btn-minus"></div> <input class="buy-offer-modal-desktop-product__default-input" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"> <div class="buy-offer-modal-desktop-product__btn-plus"></div> </div> <!-- delete --> <div class="buy-offer-modal-desktop-product__quantity--delete" style="display: none;"> <button class="buy-offer-modal-desktop-product__delete-btn">удалить</button> <button class="buy-offer-modal-desktop-product__back-btn"></button> </div> <!-- custom --> <div class="buy-offer-modal-desktop-product__quantity--custom" style="display: none;"> <button class="buy-offer-modal-desktop-product__back-btn customQuantityBackButton"></button> <div class="buy-offer-modal-desktop-product__custom-input-wrapper"> <div class="buy-offer-modal-desktop-product__custom-alert" style="display: none;">oсталось: N шт</div> <input class="buy-offer-modal-desktop-product__custom-input" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a href="" class="buy-offer-modal-desktop-product__buy-btn"></a> </div> </div> </div> </div> <!-- panel --> <div class="buy-offer-modal-desktop__panel buy-offer-modal-desktop-panel"> <div class="buy-offer-modal-desktop-panel__title">всего <span>${countFromCart}</span> <span class="buy-offer-modal-desktop-panel__title-productWord">${endingGenerated}</span> в корзине на сумму:</div> <span class="buy-offer-modal-desktop-panel__price-output">${reTotalFromCart}</span> <div class="buy-offer-modal-desktop-panel__btns"> <a href="/cart" class="buy-offer-modal-desktop-panel__cart-btn">перейти в корзину</a> <a href="#" class="buy-offer-modal-desktop-panel__stay-btn">продолжить покупки</a> </div> </div> </div> <div class="buy-offer-modal-desktop__hide-input"> <input type="checkbox" class="buy-offer-modal-desktop__hide-input-checkbox" id="buy-offer-modal-desktop__hide-modal" name="hide-modal" value="yes"> <label for="buy-offer-modal-desktop__hide-modal">Больше не показывать это окно</label> </div> </div> `; body.appendChild(buyOfferModalDesktop); buyOfferModalDesktop.style.display = 'block'; body.classList.add('page-body__no-scroll'); offerCardDesktopBuyModalLocalStorageSwitcherHide(); offerCardDesktopBuyModalCloseMech(); stickyHeaderDesktopCartCountUpdate(); //counter mech in afterBuy modal const afterBuyModalMinusButton = document.querySelector('.buy-offer-modal-desktop-product__btn-minus'); const afterBuyModalInput = document.querySelector('.buy-offer-modal-desktop-product__default-input'); const afterBuyModalPlusButton = document.querySelector('.buy-offer-modal-desktop-product__btn-plus'); const afterBuyModalQuantityAlert = document.querySelector('.buy-offer-modal-desktop-product__alert'); const quantityDeleteButton = document.querySelector('.buy-offer-modal-desktop-product__delete-btn'); const quantityBackButton = document.querySelector('.buy-offer-modal-desktop-product__back-btn'); const customQuantityInput = document.querySelector('.buy-offer-modal-desktop-product__custom-input'); const customQuantityBuyBtn = document.querySelector('.buy-offer-modal-desktop-product__buy-btn'); const afterBuyModalQuantityParentBlock = document.querySelector('.buy-offer-modal-desktop-product__quantity'); const afterBuyModalQuantityDeleteParentBlock = document.querySelector('.buy-offer-modal-desktop-product__quantity--delete'); const afterBuyModalQuantityCustomParentBlock = document.querySelector('.buy-offer-modal-desktop-product__quantity--custom'); //function for checking availability and hide plus-btn if it`s required IN MODAL function checkAvailabilityBeforeClickModal(){ let afterBuyModalCounterBlock = document.querySelector('.buy-offer-modal-desktop-product__default-input'); let afterBuyModalCounterBlockPlaceholder = afterBuyModalCounterBlock.placeholder; if(Number(afterBuyModalCounterBlockPlaceholder) >= Number(availability)){ // console.warn('afterBuyModalCounterBlockPlaceholder >= availability'); afterBuyModalQuantityAlert.style.display = 'block'; afterBuyModalQuantityAlert.innerText = `oсталось: ${availability} шт`; afterBuyModalPlusButton.classList.remove('buy-offer-modal-desktop-product__btn-plus'); afterBuyModalPlusButton.classList.add('buy-offer-modal-desktop-product__btn-plus--disable'); afterBuyModalInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClickModal(); //Modal buy Mechanics!!! afterBuyModalMinusButton.addEventListener('click', function() { let afterBuyModalCounterBlock = document.querySelector('.buy-offer-modal-desktop-product__default-input'); let afterBuyModalCounterBlockPlaceholder = afterBuyModalCounterBlock.placeholder; if(afterBuyModalCounterBlock.placeholder == '1'){ // console.warn('ONLY 1 Item in modalCart - no action') afterBuyModalQuantityParentBlock.style.display = 'none'; afterBuyModalQuantityDeleteParentBlock.style.display = 'flex'; //Quantity DELETE mech in MODAL quantityDeleteButton.addEventListener('click', function(){ const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); }else{ const response = xhr.response; let countFromCart = response.count; let modalBlockParent = document.querySelector('.buy-offer-modal-desktop'); modalBlockParent.style.display = 'none'; body.classList.remove('page-body__no-scroll'); modalBlockParent.remove(); stickyHeaderDesktop.style.top = '0'; //Quantity + - hidden quantityParent.remove(); quantityCustomParent.remove(); //Fast buy & buy btn onn currentFastBtn.style.display = 'block'; thisBtn.style.display = 'block'; //cart counter update cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); } } xhr.send(params); }); quantityBackButton.addEventListener('click', function(){ afterBuyModalQuantityDeleteParentBlock.style.display = 'none'; afterBuyModalQuantityParentBlock.style.display = 'flex'; }); }else{ // Mechanics after minusBUtton on afterBuy modal window const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ // If 1 offer in afterBuyCounterBlock checking // dynamic data from cart const response = xhr.response; let countFromCart = response.count; let totalFromCart = response.total; let stringTotalFromCart = totalFromCart.toString(); let reTotalFromCart = stringTotalFromCart.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); let modalCountBlock = document.querySelector('.buy-offer-modal-desktop-panel__title span'); let modalCountBlockProductTag = document.querySelector('.buy-offer-modal-desktop-panel__title-productWord'); let modalTotalBlock = document.querySelector('.buy-offer-modal-desktop-panel__price-output'); const endingGenerated = endingGenerate(countFromCart); modalCountBlock.innerText = countFromCart; modalTotalBlock.innerText = reTotalFromCart; modalCountBlockProductTag.innerText = endingGenerated; --afterBuyModalCounterBlock.placeholder; afterBuyInput.placeholder = --afterBuyModalCounterBlockPlaceholder; customQuantityInput.value = afterBuyModalCounterBlockPlaceholder; afterBuyModalPlusButton.classList.remove('buy-offer-modal-desktop-product__btn-plus--disable'); afterBuyModalPlusButton.classList.add('buy-offer-modal-desktop-product__btn-plus'); afterBuyModalInput.style.pointerEvents = 'auto'; afterBuyModalQuantityAlert.innerText = ` `; //cart counter update cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); } } xhr.send(params); } }); afterBuyModalPlusButton.addEventListener('click', function(){ let afterBuyModalCounterBlock = document.querySelector('.buy-offer-modal-desktop-product__default-input'); let afterBuyModalCounterBlockPlaceholder = afterBuyModalCounterBlock.placeholder; // Mechanics after plusBUtton on afterBuy modal window //availability checkout const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardDesktopAfterBuyModalCounter PlusClick ajax error'); }else{ // dynamic data from cart const response = xhr.response; let countFromCart = response.count; let totalFromCart = response.total; let stringTotalFromCart = totalFromCart.toString(); let reTotalFromCart = stringTotalFromCart.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); let modalCountBlock = document.querySelector('.buy-offer-modal-desktop-panel__title span'); let modalCountBlockProductTag = document.querySelector('.buy-offer-modal-desktop-panel__title-productWord'); let modalTotalBlock = document.querySelector('.buy-offer-modal-desktop-panel__price-output'); const endingGenerated = endingGenerate(countFromCart); modalCountBlock.innerText = countFromCart; modalTotalBlock.innerText = reTotalFromCart; modalCountBlockProductTag.innerText = endingGenerated; ++afterBuyModalCounterBlock.placeholder; afterBuyInput.placeholder = ++afterBuyModalCounterBlockPlaceholder; customQuantityInput.value = afterBuyModalCounterBlockPlaceholder; //cart counter update cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); checkAvailabilityBeforeClickModal(); } } xhr.send(params); }); afterBuyModalInput.addEventListener('click', function(){ afterBuyModalQuantityParentBlock.style.display = 'none'; afterBuyModalQuantityCustomParentBlock.style.display = 'flex'; const customQuantityInput = document.querySelector('.buy-offer-modal-desktop-product__custom-input'); const customQuantityBackButton = document.querySelector('.customQuantityBackButton'); localStorage.setItem('customQuantityInputValue', customQuantityInput.value); customQuantityInput.focus(); customQuantityInput.addEventListener('input', function updateInputVal(e){ const customQuantityInputValue = customQuantityInput.value; const customQuantityAlert = document.querySelector('.buy-offer-modal-desktop-product__custom-alert'); // console.warn(customQuantityInputValue); if(Number(customQuantityInput.value) < Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); // console.warn(`КАСТОМНЫЙ ИНПУТ ${customQuantityInputValue}`); // console.warn(`ОСТАТОК ${availability}`); localStorage.setItem('customQuantityInputValue', customQuantityInputValue); }else if(Number(customQuantityInput.value) >= Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); // console.warn(`КАСТОМНЫЙ ИНПУТ ${customQuantityInputValue}`); // console.warn(`ОСТАТОК ${availability}`); customQuantityAlert.style.display = 'block'; customQuantityAlert.innerText = `oсталось: ${availability} шт`; customQuantityInput.value = availability; localStorage.setItem('customQuantityInputValue', availability); }else if(typeof availability === 'string'){ localStorage.setItem('customQuantityInputValue', customQuantityInputValue); } }) customQuantityBackButton.addEventListener('click', function(){ afterBuyModalQuantityParentBlock.style.display = 'flex'; afterBuyModalQuantityCustomParentBlock.style.display = 'none'; }); }); customQuantityBuyBtn.addEventListener('click', function (e) { e.preventDefault(); // console.warn('CLICK buyBtnCustomQuantity'); let customQuantityInputValue = localStorage.getItem('customQuantityInputValue'); if(customQuantityInputValue == ''){ console.warn('customQuantityInputValue === empty string'); }else{ // console.warn('customQuantityInputValue'); // console.warn(customQuantityInputValue); let thisBtn = this; thisBtn.classList.remove('buy-offer-modal-desktop-product__buy-btn'); thisBtn.classList.add('buy-offer-modal-desktop-product__buy-btn--load'); thisBtn.innerHTML = `<div class="desktop-modal-buy__buy-btn-preloader"></div>`; function sendOfferToCartModalFromCustomBuy(){ const params = new URLSearchParams(); params.set('id', key); params.append('qty', customQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('modalCustomQuantityBuyButtonMech ajax error'); } else { // console.warn('modalCustomQuantityBuyButtonMech ajax SUCCESS'); thisBtn.classList.remove('buy-offer-modal-desktop-product__buy-btn--load'); thisBtn.classList.add('buy-offer-modal-desktop-product__buy-btn'); thisBtn.innerHTML = ` `; // dynamic data from cart const response = xhr.response; let countFromCart = response.count; let totalFromCart = response.total; let stringTotalFromCart = totalFromCart.toString(); let reTotalFromCart = stringTotalFromCart.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); let modalCountBlock = document.querySelector('.buy-offer-modal-desktop-panel__title span'); let modalCountBlockProductTag = document.querySelector('.buy-offer-modal-desktop-panel__title-productWord'); let modalTotalBlock = document.querySelector('.buy-offer-modal-desktop-panel__price-output'); const endingGenerated = endingGenerate(countFromCart); // console.warn(availability); modalCountBlock.innerText = countFromCart; modalTotalBlock.innerText = reTotalFromCart; modalCountBlockProductTag.innerText = endingGenerated; //custom quantity synh on NO modal buy btns afterBuyInput.placeholder = customQuantityInputValue; afterBuyModalInput.placeholder = customQuantityInputValue; afterBuyModalQuantityCustomParentBlock.style.display = 'none'; afterBuyModalQuantityParentBlock.style.display = 'flex'; //cart counter update cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); checkAvailabilityBeforeClickModal(); } } xhr.send(params); } setTimeout(sendOfferToCartModalFromCustomBuy, 300); } }); }else{ let currentFastBtnSuccess = parentBuyBlockDesktop.querySelector('.desktop-buy__fast-buy-btn--success'); if(currentFastBtnSuccess){ currentFastBtnSuccess.style.display = 'none'; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Add quantity btns instead buy btn let quantityParent = document.createElement('div'); quantityParent.classList.add('desktop-buy-quantity'); let quantityCustomParent = document.createElement('div'); quantityCustomParent.classList.add('desktop-buy-quantity--custom'); quantityParent.innerHTML = ` <div class="desktop-buy-quantity__btn-minus" data-key="${key}"></div> <input class="desktop-buy-quantity__default-input" placeholder="1"> <div class="desktop-buy-quantity__btn-plus" data-key="${key}"></div> `; quantityCustomParent.innerHTML = ` <div class="desktop-buy-quantity__back-btn"></div> <div class="desktop-buy-quantity__custom-input-wrapper"> <input class="desktop-buy-quantity__custom-input" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a class="desktop-buy-quantity__buy-btn"></a> </div> `; parentBuyBlockDesktop.appendChild(quantityParent); parentBuyBlockDesktop.appendChild(quantityCustomParent); const afterBuyMinusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-minus'); const afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyCustomInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyPlusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-plus'); const afterBuyQuantityBuyButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__buy-btn'); //Close offer-buy modal function offerCardDesktopBuyModalCloseMech(){ let modalBlockParent = document.querySelector('.buy-offer-modal-desktop'); let modalBlockCloseBtn = document.querySelector('.buy-offer-modal-desktop__close-btn'); let modalBlockStayBtn = document.querySelector('.buy-offer-modal-desktop-panel__stay-btn'); let body = document.querySelector('body'); let stickyHeaderDesktop = document.querySelector('.sticky-header-desktop'); if(modalBlockParent === null){ }else{ modalBlockCloseBtn.addEventListener('click', function(){ modalBlockParent.style.display = 'none'; body.classList.remove('page-body__no-scroll'); modalBlockParent.remove(); stickyHeaderDesktop.style.top = '0'; //reset custom quantity value localStorage.setItem('customQuantityInputValue', ''); checkAvailabilityBeforeClick(); }) modalBlockStayBtn.addEventListener('click', function(e){ e.preventDefault(); modalBlockParent.style.display = 'none'; body.classList.remove('page-body__no-scroll'); modalBlockParent.remove(); stickyHeaderDesktop.style.top = '0'; //reset custom quantity value localStorage.setItem('customQuantityInputValue', ''); checkAvailabilityBeforeClick(); }) } } //function for checking availability and hide plus-btn if it`s required function checkAvailabilityBeforeClick(){ let afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyInputPlaceholder = afterBuyInput.placeholder; if(Number(afterBuyInputPlaceholder) >= Number(availability)){ // console.warn('afterBuyInputPlaceholder >= availability'); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus--disable'); afterBuyInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClick(); //NO modal buy Mechanics!!! - Mechs in offer-desktop-card afterBuyMinusButton.addEventListener('click', function(){ //Mechanic after click on Minus button if(afterBuyInput.placeholder == '1'){ const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Quantity + - hidden quantityParent.remove(); quantityCustomParent.remove(); //Fast buy & buy btn onn currentFastBtnSuccess.style.display = 'block'; thisBtn.style.display = 'block'; } } xhr.send(params); }else{ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ // If 1 offer in afterBuyInputBlock checking const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); --afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus--disable'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus'); afterBuyInput.style.pointerEvents = 'auto'; } } xhr.send(params); } }); afterBuyPlusButton.addEventListener('click', function(){ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); ++afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; checkAvailabilityBeforeClick(); } } xhr.send(params); }); afterBuyInput.addEventListener('click', function(){ quantityParent.style.display = 'none'; quantityCustomParent.style.display = 'flex'; const afterBuyCustomQuantityInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyCustomQuantityBackBtn = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__back-btn'); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyInput.placeholder); afterBuyCustomQuantityInput.value = afterBuyInput.placeholder; afterBuyCustomQuantityInput.focus(); afterBuyCustomQuantityInput.addEventListener('input', function updateCustomInputValue(e){ const afterBuyCustomQuantityInputValue = afterBuyCustomQuantityInput.value; if(Number(afterBuyCustomQuantityInput.value) < Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); }else if(Number(afterBuyCustomQuantityInput.value) >= Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyCustomQuantityInput.value = availability; localStorage.setItem('noModalCustomQuantityInputValue', availability); }else if(typeof availability === 'string'){ localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); } }); afterBuyCustomQuantityBackBtn.addEventListener('click', function(){ quantityCustomParent.style.display = 'none'; quantityParent.style.display = 'flex'; }); }); afterBuyQuantityBuyButton.addEventListener('click', function(e){ e.preventDefault(); let noModalCustomQuantityInputValue = localStorage.getItem('noModalCustomQuantityInputValue'); if(noModalCustomQuantityInputValue == ''){ // console.warn('noModalCustomQuantityInputValue === empty string'); }else{ // console.warn('noModalCustomQuantityInputValue'); // console.warn(noModalCustomQuantityInputValue); let thisBtn = this; thisBtn.classList.remove('desktop-buy-quantity__buy-btn'); thisBtn.classList.add('desktop-buy-quantity__buy-btn--load'); thisBtn.innerHTML = `<div class="desktop-custom-quantity-buy__buy-btn-preloader"></div>`; function sendOfferToCartDesktopCustomQuamnity(){ const params = new URLSearchParams(); params.set('id', key); params.append('qty', noModalCustomQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('modalCustomQuantityBuyButtonMech ajax error'); } else { // console.warn('modalCustomQuantityBuyButtonMech ajax SUCCESS'); thisBtn.classList.remove('desktop-buy-quantity__buy-btn--load'); thisBtn.classList.add('desktop-buy-quantity__buy-btn'); thisBtn.innerHTML = ` `; // dynamic data from cart const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); afterBuyInput.placeholder = noModalCustomQuantityInputValue; quantityParent.style.display = 'flex'; quantityCustomParent.style.display = 'none'; checkAvailabilityBeforeClick(); } } xhr.send(params); } setTimeout(sendOfferToCartDesktopCustomQuamnity, 300); } }); //ModalBuy mech start here let picForModalsOffer = offerPicture.innerHTML; let vendorCodeForModalsOffer = offerVendorCode.innerHTML; let titleForModalsOffer = offerTitle.innerHTML; let manufacturerForModalsOffer = offerManufacturer.innerHTML; let priceForModalsOffer = offerPrice.innerHTML; //dynamic data from cart // let countFromCart = response.count; let totalFromCart = response.total; let stringTotalFromCart = totalFromCart.toString(); let reTotalFromCart = stringTotalFromCart.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); //Вариативное окончание "Товара" function endingGenerate(int, array) { return (array = array || ['товар', 'товара', 'товаров']) && array[(int % 100 > 4 && int % 100 < 20) ? 2 : [2, 0, 1, 1, 1, 2][(int % 10 < 5) ? int % 10 : 5]]; } const endingGenerated = endingGenerate(countFromCart); cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; trackCartCount(); let buyOfferModalDesktop = document.createElement("section"); buyOfferModalDesktop.classList.add('buy-offer-modal-desktop'); buyOfferModalDesktop.innerHTML = `<div class="buy-offer-modal-desktop__blur"></div> <div class="buy-offer-modal-desktop__wrapper"> <div class="buy-offer-modal-desktop__title-wrapper"> <div class="buy-offer-modal-desktop__title">Товар успешно добавлен в корзину</div> <div class="buy-offer-modal-desktop__close-btn"></div> </div> <div class="buy-offer-modal-desktop__panel-wrapper"> <!-- product --> <div class="buy-offer-modal-desktop__product buy-offer-modal-desktop-product"> <div class="buy-offer-modal-desktop-product__description"> <div class="buy-offer-modal-desktop-product__picture"> <a href="${offerPicture.href}" target="_blank"> ${picForModalsOffer} </a> </div> <div class="buy-offer-modal-desktop-product__description-inner"> <div class="buy-offer-modal-desktop-product__vendor-code">Артикул: <span>${vendorCodeForModalsOffer}</span></div> <a href="${offerPicture.href}" class="buy-offer-modal-desktop-product__title" target="_blank"> ${titleForModalsOffer} </a> <div class="buy-offer-modal-desktop-product__quality-wrapper"> <div class="buy-offer-modal-desktop-product__manufactor">${manufacturerForModalsOffer}</div> <div class="buy-offer-modal-desktop-product__quality" style="display:none">genuine</div> </div> </div> </div> <div class="buy-offer-modal-desktop-product__price-panel"> <div class="buy-offer-modal-desktop-product__price">Цена (шт):<span>${priceForModalsOffer}</span></div> <!-- default --> <div class="buy-offer-modal-desktop-product__quantity"> <div class="buy-offer-modal-desktop-product__alert" style="display: none;">oсталось: 12 шт</div> <div class="buy-offer-modal-desktop-product__btn-minus"></div> <input class="buy-offer-modal-desktop-product__default-input" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength);"> <div class="buy-offer-modal-desktop-product__btn-plus"></div> </div> <!-- delete --> <div class="buy-offer-modal-desktop-product__quantity--delete" style="display: none;"> <button class="buy-offer-modal-desktop-product__delete-btn">удалить</button> <button class="buy-offer-modal-desktop-product__back-btn"></button> </div> <!-- custom --> <div class="buy-offer-modal-desktop-product__quantity--custom" style="display: none;"> <button class="buy-offer-modal-desktop-product__back-btn customQuantityBackButton"></button> <div class="buy-offer-modal-desktop-product__custom-input-wrapper"> <div class="buy-offer-modal-desktop-product__custom-alert" style="display: none;">oсталось: N шт</div> <input class="buy-offer-modal-desktop-product__custom-input" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a href="" class="buy-offer-modal-desktop-product__buy-btn"></a> </div> </div> </div> </div> <!-- panel --> <div class="buy-offer-modal-desktop__panel buy-offer-modal-desktop-panel"> <div class="buy-offer-modal-desktop-panel__title">всего <span>${countFromCart}</span> <span class="buy-offer-modal-desktop-panel__title-productWord">${endingGenerated}</span> в корзине на сумму:</div> <span class="buy-offer-modal-desktop-panel__price-output">${reTotalFromCart}</span> <div class="buy-offer-modal-desktop-panel__btns"> <a href="/cart" class="buy-offer-modal-desktop-panel__cart-btn">перейти в корзину</a> <a href="#" class="buy-offer-modal-desktop-panel__stay-btn">продолжить покупки</a> </div> </div> </div> <div class="buy-offer-modal-desktop__hide-input"> <input type="checkbox" class="buy-offer-modal-desktop__hide-input-checkbox" id="buy-offer-modal-desktop__hide-modal" name="hide-modal" value="yes"> <label for="buy-offer-modal-desktop__hide-modal">Больше не показывать это окно</label> </div> </div> `; body.appendChild(buyOfferModalDesktop); buyOfferModalDesktop.style.display = 'block'; body.classList.add('page-body__no-scroll'); offerCardDesktopBuyModalLocalStorageSwitcherHide(); offerCardDesktopBuyModalCloseMech(); stickyHeaderDesktopCartCountUpdate(); //counter mech in afterBuy modal const afterBuyModalMinusButton = document.querySelector('.buy-offer-modal-desktop-product__btn-minus'); const afterBuyModalInput = document.querySelector('.buy-offer-modal-desktop-product__default-input'); const afterBuyModalPlusButton = document.querySelector('.buy-offer-modal-desktop-product__btn-plus'); const afterBuyModalQuantityAlert = document.querySelector('.buy-offer-modal-desktop-product__alert'); const quantityDeleteButton = document.querySelector('.buy-offer-modal-desktop-product__delete-btn'); const quantityBackButton = document.querySelector('.buy-offer-modal-desktop-product__back-btn'); const customQuantityInput = document.querySelector('.buy-offer-modal-desktop-product__custom-input'); const customQuantityBuyBtn = document.querySelector('.buy-offer-modal-desktop-product__buy-btn'); const afterBuyModalQuantityParentBlock = document.querySelector('.buy-offer-modal-desktop-product__quantity'); const afterBuyModalQuantityDeleteParentBlock = document.querySelector('.buy-offer-modal-desktop-product__quantity--delete'); const afterBuyModalQuantityCustomParentBlock = document.querySelector('.buy-offer-modal-desktop-product__quantity--custom'); //function for checking availability and hide plus-btn if it`s required IN MODAL function checkAvailabilityBeforeClickModal(){ let afterBuyModalCounterBlock = document.querySelector('.buy-offer-modal-desktop-product__default-input'); let afterBuyModalCounterBlockPlaceholder = afterBuyModalCounterBlock.placeholder; if(Number(afterBuyModalCounterBlockPlaceholder) >= Number(availability)){ // console.warn('afterBuyModalCounterBlockPlaceholder >= availability'); afterBuyModalQuantityAlert.style.display = 'block'; afterBuyModalQuantityAlert.innerText = `oсталось: ${availability} шт`; afterBuyModalPlusButton.classList.remove('buy-offer-modal-desktop-product__btn-plus'); afterBuyModalPlusButton.classList.add('buy-offer-modal-desktop-product__btn-plus--disable'); afterBuyModalInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClickModal(); //Modal buy Mechanics!!! afterBuyModalMinusButton.addEventListener('click', function() { let afterBuyModalCounterBlock = document.querySelector('.buy-offer-modal-desktop-product__default-input'); let afterBuyModalCounterBlockPlaceholder = afterBuyModalCounterBlock.placeholder; if(afterBuyModalCounterBlock.placeholder == '1'){ // console.warn('ONLY 1 Item in modalCart - no action') afterBuyModalQuantityParentBlock.style.display = 'none'; afterBuyModalQuantityDeleteParentBlock.style.display = 'flex'; //Quantity DELETE mech in MODAL quantityDeleteButton.addEventListener('click', function(){ const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); }else{ const response = xhr.response; let countFromCart = response.count; let modalBlockParent = document.querySelector('.buy-offer-modal-desktop'); modalBlockParent.style.display = 'none'; body.classList.remove('page-body__no-scroll'); modalBlockParent.remove(); stickyHeaderDesktop.style.top = '0'; //Quantity + - hidden quantityParent.remove(); quantityCustomParent.remove(); //Fast buy & buy btn onn currentFastBtnSuccess.style.display = 'block'; thisBtn.style.display = 'block'; //cart counter update cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); } } xhr.send(params); }); quantityBackButton.addEventListener('click', function(){ afterBuyModalQuantityDeleteParentBlock.style.display = 'none'; afterBuyModalQuantityParentBlock.style.display = 'flex'; }); }else{ // Mechanics after minusBUtton on afterBuy modal window const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ // If 1 offer in afterBuyCounterBlock checking // dynamic data from cart const response = xhr.response; let countFromCart = response.count; let totalFromCart = response.total; let stringTotalFromCart = totalFromCart.toString(); let reTotalFromCart = stringTotalFromCart.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); let modalCountBlock = document.querySelector('.buy-offer-modal-desktop-panel__title span'); let modalCountBlockProductTag = document.querySelector('.buy-offer-modal-desktop-panel__title-productWord'); let modalTotalBlock = document.querySelector('.buy-offer-modal-desktop-panel__price-output'); const endingGenerated = endingGenerate(countFromCart); modalCountBlock.innerText = countFromCart; modalTotalBlock.innerText = reTotalFromCart; modalCountBlockProductTag.innerText = endingGenerated; --afterBuyModalCounterBlock.placeholder; afterBuyInput.placeholder = --afterBuyModalCounterBlockPlaceholder; customQuantityInput.value = afterBuyModalCounterBlockPlaceholder; afterBuyModalPlusButton.classList.remove('buy-offer-modal-desktop-product__btn-plus--disable'); afterBuyModalPlusButton.classList.add('buy-offer-modal-desktop-product__btn-plus'); afterBuyModalInput.style.pointerEvents = 'auto'; afterBuyModalQuantityAlert.innerText = ` `; //cart counter update cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); } } xhr.send(params); } }); afterBuyModalPlusButton.addEventListener('click', function(){ let afterBuyModalCounterBlock = document.querySelector('.buy-offer-modal-desktop-product__default-input'); let afterBuyModalCounterBlockPlaceholder = afterBuyModalCounterBlock.placeholder; // Mechanics after plusBUtton on afterBuy modal window //availability checkout const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardDesktopAfterBuyModalCounter PlusClick ajax error'); }else{ // dynamic data from cart const response = xhr.response; let countFromCart = response.count; let totalFromCart = response.total; let stringTotalFromCart = totalFromCart.toString(); let reTotalFromCart = stringTotalFromCart.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); let modalCountBlock = document.querySelector('.buy-offer-modal-desktop-panel__title span'); let modalCountBlockProductTag = document.querySelector('.buy-offer-modal-desktop-panel__title-productWord'); let modalTotalBlock = document.querySelector('.buy-offer-modal-desktop-panel__price-output'); const endingGenerated = endingGenerate(countFromCart); modalCountBlock.innerText = countFromCart; modalTotalBlock.innerText = reTotalFromCart; modalCountBlockProductTag.innerText = endingGenerated; ++afterBuyModalCounterBlock.placeholder; afterBuyInput.placeholder = ++afterBuyModalCounterBlockPlaceholder; customQuantityInput.value = afterBuyModalCounterBlockPlaceholder; //cart counter update cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); checkAvailabilityBeforeClickModal(); } } xhr.send(params); }); afterBuyModalInput.addEventListener('click', function(){ afterBuyModalQuantityParentBlock.style.display = 'none'; afterBuyModalQuantityCustomParentBlock.style.display = 'flex'; const customQuantityInput = document.querySelector('.buy-offer-modal-desktop-product__custom-input'); const customQuantityBackButton = document.querySelector('.customQuantityBackButton'); localStorage.setItem('customQuantityInputValue', customQuantityInput.value); customQuantityInput.focus(); customQuantityInput.addEventListener('input', function updateInputVal(e){ const customQuantityInputValue = customQuantityInput.value; const customQuantityAlert = document.querySelector('.buy-offer-modal-desktop-product__custom-alert'); // console.warn(customQuantityInputValue); if(Number(customQuantityInput.value) < Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); // console.warn(`КАСТОМНЫЙ ИНПУТ ${customQuantityInputValue}`); // console.warn(`ОСТАТОК ${availability}`); localStorage.setItem('customQuantityInputValue', customQuantityInputValue); }else if(Number(customQuantityInput.value) >= Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); // console.warn(`КАСТОМНЫЙ ИНПУТ ${customQuantityInputValue}`); // console.warn(`ОСТАТОК ${availability}`); customQuantityAlert.style.display = 'block'; customQuantityAlert.innerText = `oсталось: ${availability} шт`; customQuantityInput.value = availability; localStorage.setItem('customQuantityInputValue', availability); }else if(typeof availability === 'string'){ localStorage.setItem('customQuantityInputValue', customQuantityInputValue); } }) customQuantityBackButton.addEventListener('click', function(){ afterBuyModalQuantityParentBlock.style.display = 'flex'; afterBuyModalQuantityCustomParentBlock.style.display = 'none'; }); }); customQuantityBuyBtn.addEventListener('click', function (e) { e.preventDefault(); // console.warn('CLICK buyBtnCustomQuantity'); let customQuantityInputValue = localStorage.getItem('customQuantityInputValue'); if(customQuantityInputValue == ''){ // console.warn('customQuantityInputValue === empty string'); }else{ // console.warn('customQuantityInputValue'); // console.warn(customQuantityInputValue); let thisBtn = this; thisBtn.classList.remove('buy-offer-modal-desktop-product__buy-btn'); thisBtn.classList.add('buy-offer-modal-desktop-product__buy-btn--load'); thisBtn.innerHTML = `<div class="desktop-modal-buy__buy-btn-preloader"></div>`; function sendOfferToCartModalFromCustomBuy(){ const params = new URLSearchParams(); params.set('id', key); params.append('qty', customQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('modalCustomQuantityBuyButtonMech ajax error'); } else { // console.warn('modalCustomQuantityBuyButtonMech ajax SUCCESS'); thisBtn.classList.remove('buy-offer-modal-desktop-product__buy-btn--load'); thisBtn.classList.add('buy-offer-modal-desktop-product__buy-btn'); thisBtn.innerHTML = ` `; // dynamic data from cart const response = xhr.response; let countFromCart = response.count; let totalFromCart = response.total; let stringTotalFromCart = totalFromCart.toString(); let reTotalFromCart = stringTotalFromCart.replace(/(\d)(?=(\d{3})+$)/g, '$1 '); let modalCountBlock = document.querySelector('.buy-offer-modal-desktop-panel__title span'); let modalCountBlockProductTag = document.querySelector('.buy-offer-modal-desktop-panel__title-productWord'); let modalTotalBlock = document.querySelector('.buy-offer-modal-desktop-panel__price-output'); const endingGenerated = endingGenerate(countFromCart); // console.warn(availability); modalCountBlock.innerText = countFromCart; modalTotalBlock.innerText = reTotalFromCart; modalCountBlockProductTag.innerText = endingGenerated; //custom quantity synh on NO modal buy btns afterBuyInput.placeholder = customQuantityInputValue; afterBuyModalInput.placeholder = customQuantityInputValue; afterBuyModalQuantityCustomParentBlock.style.display = 'none'; afterBuyModalQuantityParentBlock.style.display = 'flex'; //cart counter update cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); checkAvailabilityBeforeClickModal(); } } xhr.send(params); } setTimeout(sendOfferToCartModalFromCustomBuy, 300); } }); } } } } xhr.send(params); } setTimeout(function(){ sendOfferToCart(); }, 400); }); } }else if(modalPar === "noModal"){ for (let i = 0; i < offerbuyBtns.length; i++){ offerbuyBtns[i].addEventListener('click', function buyBtnFunc(e) { e.preventDefault(); //reset custom quantity value localStorage.setItem('noModalCustomQuantityInputValue', ''); let thisBtn = this; thisBtn.classList.remove('desktop-buy__buy-btn'); thisBtn.classList.add('desktop-buy__buy-btn--load'); thisBtn.innerHTML = `<div class="desktop-buy__buy-btn-preloader"></div>`; let key = encodeURIComponent(thisBtn.dataset.key); let availability = thisBtn.dataset.availability; function sendOfferToCart() { const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardDesktopBuyButtonMech ajax error'); errorBannerDesktopRemove(); errorBannerDesktop(); thisBtn.classList.remove('desktop-buy__buy-btn--load'); thisBtn.classList.add('desktop-buy__buy-btn'); thisBtn.innerHTML = ` `; }else{ const response = xhr.response; let currentPreloader = thisBtn.querySelector('.desktop-buy__buy-btn-preloader'); currentPreloader.remove(); thisBtn.classList.remove('desktop-buy__buy-btn--load'); thisBtn.classList.add('desktop-buy__buy-btn'); thisBtn.innerHTML = ` `; let parentBuyBlockDesktop = thisBtn.parentElement; let currentFastBtn = parentBuyBlockDesktop.querySelector('.desktop-buy__fast-buy-btn'); let desktopCardItemInner = parentBuyBlockDesktop.parentElement; //Availability sign of offer let offerCardAvailableSign = desktopCardItemInner.querySelector('.desktop-description__shop'); if(currentFastBtn){ //Hide buttons thisBtn.style.display = 'none'; currentFastBtn.style.display = 'none'; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Add quantity btns instead buy btn let quantityParent = document.createElement('div'); quantityParent.classList.add('desktop-buy-quantity'); let quantityCustomParent = document.createElement('div'); quantityCustomParent.classList.add('desktop-buy-quantity--custom'); quantityParent.innerHTML = ` <div class="desktop-buy-quantity__btn-minus" data-key="${key}"></div> <input class="desktop-buy-quantity__default-input" placeholder="1"> <div class="desktop-buy-quantity__btn-plus" data-key="${key}"></div> `; quantityCustomParent.innerHTML = ` <div class="desktop-buy-quantity__back-btn"></div> <div class="desktop-buy-quantity__custom-input-wrapper"> <input class="desktop-buy-quantity__custom-input" pattern="[0-9]*" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a class="desktop-buy-quantity__buy-btn"></a> </div> `; parentBuyBlockDesktop.appendChild(quantityParent); parentBuyBlockDesktop.appendChild(quantityCustomParent); const afterBuyMinusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-minus'); const afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyCustomInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyPlusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-plus'); const afterBuyQuantityBuyButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__buy-btn'); //function for checking availability and hide plus-btn if it`s required function checkAvailabilityBeforeClick(){ let afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyInputPlaceholder = afterBuyInput.placeholder; if(Number(afterBuyInputPlaceholder) >= Number(availability)){ // console.warn('afterBuyInputPlaceholder >= availability'); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus--disable'); afterBuyInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClick(); afterBuyMinusButton.addEventListener('click', function(){ //Mechanic after click on Minus button if(afterBuyInput.placeholder == '1'){ const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Quantity + - hidden quantityParent.remove(); quantityCustomParent.remove(); //Fast buy & buy btn onn currentFastBtn.style.display = 'block'; thisBtn.style.display = 'block'; } } xhr.send(params); }else{ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ // If 1 offer in afterBuyInputBlock checking const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); --afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus--disable'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus'); afterBuyInput.style.pointerEvents = 'auto'; } } xhr.send(params); } }); afterBuyPlusButton.addEventListener('click', function(){ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); ++afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; checkAvailabilityBeforeClick(); } } xhr.send(params); }); afterBuyInput.addEventListener('click', function(){ quantityParent.style.display = 'none'; quantityCustomParent.style.display = 'flex'; const afterBuyCustomQuantityInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyCustomQuantityBackBtn = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__back-btn'); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyInput.placeholder); afterBuyCustomQuantityInput.value = afterBuyInput.placeholder; afterBuyCustomQuantityInput.focus(); afterBuyCustomQuantityInput.addEventListener('input', function updateCustomInputValue(e){ const afterBuyCustomQuantityInputValue = afterBuyCustomQuantityInput.value; if(Number(afterBuyCustomQuantityInput.value) < Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); }else if(Number(afterBuyCustomQuantityInput.value) >= Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyCustomQuantityInput.value = availability; localStorage.setItem('noModalCustomQuantityInputValue', availability); }else if(typeof availability === 'string'){ localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); } }); afterBuyCustomQuantityBackBtn.addEventListener('click', function(){ quantityCustomParent.style.display = 'none'; quantityParent.style.display = 'flex'; }); }); afterBuyQuantityBuyButton.addEventListener('click', function(e){ e.preventDefault(); let noModalCustomQuantityInputValue = localStorage.getItem('noModalCustomQuantityInputValue'); if(noModalCustomQuantityInputValue == ''){ // console.warn('noModalCustomQuantityInputValue === empty string'); }else{ // console.warn('noModalCustomQuantityInputValue'); // console.warn(noModalCustomQuantityInputValue); let thisBtn = this; thisBtn.classList.remove('desktop-buy-quantity__buy-btn'); thisBtn.classList.add('desktop-buy-quantity__buy-btn--load'); thisBtn.innerHTML = `<div class="desktop-custom-quantity-buy__buy-btn-preloader"></div>`; function sendOfferToCartDesktopCustomQuamnity(){ const params = new URLSearchParams(); params.set('id', key); params.append('qty', noModalCustomQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('modalCustomQuantityBuyButtonMech ajax error'); } else { // console.warn('modalCustomQuantityBuyButtonMech ajax SUCCESS'); thisBtn.classList.remove('desktop-buy-quantity__buy-btn--load'); thisBtn.classList.add('desktop-buy-quantity__buy-btn'); thisBtn.innerHTML = ` `; // dynamic data from cart const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); afterBuyInput.placeholder = noModalCustomQuantityInputValue; quantityParent.style.display = 'flex'; quantityCustomParent.style.display = 'none'; checkAvailabilityBeforeClick(); } } xhr.send(params); } setTimeout(sendOfferToCartDesktopCustomQuamnity, 300); } }); //init parent + add tooltip offerCardDesktopBuyModalLocalStorageSwitcherHide(); }else{ let currentFastBtnSuccess = parentBuyBlockDesktop.querySelector('.desktop-buy__fast-buy-btn--success'); if(currentFastBtnSuccess){ //Hide buttons thisBtn.style.display = 'none'; currentFastBtnSuccess.style.display = 'none'; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Add quantity btns instead buy btn let quantityParent = document.createElement('div'); quantityParent.classList.add('desktop-buy-quantity'); let quantityCustomParent = document.createElement('div'); quantityCustomParent.classList.add('desktop-buy-quantity--custom'); quantityParent.innerHTML = ` <div class="desktop-buy-quantity__btn-minus" data-key="${key}"></div> <input class="desktop-buy-quantity__default-input" placeholder="1"> <div class="desktop-buy-quantity__btn-plus" data-key="${key}"></div> `; quantityCustomParent.innerHTML = ` <div class="desktop-buy-quantity__back-btn"></div> <div class="desktop-buy-quantity__custom-input-wrapper"> <input class="desktop-buy-quantity__custom-input" pattern="[0-9]*" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a class="desktop-buy-quantity__buy-btn"></a> </div> `; parentBuyBlockDesktop.appendChild(quantityParent); parentBuyBlockDesktop.appendChild(quantityCustomParent); const afterBuyMinusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-minus'); const afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyCustomInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyPlusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-plus'); const afterBuyQuantityBuyButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__buy-btn'); function checkAvailabilityBeforeClick(){ let afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyInputPlaceholder = afterBuyInput.placeholder; if(Number(afterBuyInputPlaceholder) >= Number(availability)){ // console.warn('afterBuyInputPlaceholder >= availability'); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus--disable'); afterBuyInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClick(); afterBuyMinusButton.addEventListener('click', function(){ //Mechanic after click on Minus button if(afterBuyInput.placeholder == '1'){ const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Quantity + - hidden quantityParent.remove(); quantityCustomParent.remove(); //Fast buy & buy btn onn currentFastBtnSuccess.style.display = 'block'; thisBtn.style.display = 'block'; } } xhr.send(params); }else{ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ // If 1 offer in afterBuyInputBlock checking const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); --afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus--disable'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus'); afterBuyInput.style.pointerEvents = 'auto'; } } xhr.send(params); } }); afterBuyPlusButton.addEventListener('click', function(){ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); ++afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; checkAvailabilityBeforeClick(); } } xhr.send(params); }); afterBuyInput.addEventListener('click', function(){ quantityParent.style.display = 'none'; quantityCustomParent.style.display = 'flex'; const afterBuyCustomQuantityInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyCustomQuantityBackBtn = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__back-btn'); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyInput.placeholder); afterBuyCustomQuantityInput.value = afterBuyInput.placeholder; afterBuyCustomQuantityInput.focus(); afterBuyCustomQuantityInput.addEventListener('input', function updateCustomInputValue(e){ const afterBuyCustomQuantityInputValue = afterBuyCustomQuantityInput.value; if(Number(afterBuyCustomQuantityInput.value) < Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); }else if(Number(afterBuyCustomQuantityInput.value) >= Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyCustomQuantityInput.value = availability; localStorage.setItem('noModalCustomQuantityInputValue', availability); }else if(typeof availability === 'string'){ localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); } }); afterBuyCustomQuantityBackBtn.addEventListener('click', function(){ quantityCustomParent.style.display = 'none'; quantityParent.style.display = 'flex'; }); }); afterBuyQuantityBuyButton.addEventListener('click', function(e){ e.preventDefault(); let noModalCustomQuantityInputValue = localStorage.getItem('noModalCustomQuantityInputValue'); if(noModalCustomQuantityInputValue == ''){ // console.warn('noModalCustomQuantityInputValue === empty string'); }else{ // console.warn('noModalCustomQuantityInputValue'); // console.warn(noModalCustomQuantityInputValue); let thisBtn = this; thisBtn.classList.remove('desktop-buy-quantity__buy-btn'); thisBtn.classList.add('desktop-buy-quantity__buy-btn--load'); thisBtn.innerHTML = `<div class="desktop-custom-quantity-buy__buy-btn-preloader"></div>`; function sendOfferToCartDesktopCustomQuamnity(){ const params = new URLSearchParams(); params.set('id', key); params.append('qty', noModalCustomQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('modalCustomQuantityBuyButtonMech ajax error'); } else { // console.warn('modalCustomQuantityBuyButtonMech ajax SUCCESS'); thisBtn.classList.remove('desktop-buy-quantity__buy-btn--load'); thisBtn.classList.add('desktop-buy-quantity__buy-btn'); thisBtn.innerHTML = ` `; // dynamic data from cart const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); afterBuyInput.placeholder = noModalCustomQuantityInputValue; quantityParent.style.display = 'flex'; quantityCustomParent.style.display = 'none'; checkAvailabilityBeforeClick(); } } xhr.send(params); } setTimeout(sendOfferToCartDesktopCustomQuamnity, 300); } }); //init parent + add tooltip offerCardDesktopBuyModalLocalStorageSwitcherHide(); } } } } xhr.send(params); } setTimeout(function(){ sendOfferToCart(); }, 400); }); } }else if(modalPar === null){ offerCardDesktopBuyModalLocalStorageSwitcher(); } } } } } } offerCardDesktopBuyButtonMech(); //Buy button tooltips stuff function offerCardDesktopBuyButtonTooltip(){ let buyBtns = document.querySelectorAll('.desktop-buy__buy-btn'); if(buyBtns === null){ }else{ buyBtns.forEach(item => { item.innerHTML = `<div class="desktop-buy__buy-btn-tooltip">Добавить в корзину</div>` let currentBuyTooltip = item.querySelector('.desktop-buy__buy-btn-tooltip'); item.addEventListener('mouseover', function() { currentBuyTooltip.style.visibility = 'visible'; currentBuyTooltip.style.opacity = '1'; }) item.addEventListener('mouseout', function() { currentBuyTooltip.style.visibility = 'hidden'; currentBuyTooltip.style.opacity = '0'; }) }) } } offerCardDesktopBuyButtonTooltip(); //Add to cart button Mobile ✰4 function offerCardMobileBuyButtonMech(){ let offersMobileListItems = document.querySelectorAll('.mobile-list-item'); if (offersMobileListItems === null) { }else{ for (let i = 0; i < offersMobileListItems.length; i++) { let offersMobileQuantityBlock = offersMobileListItems[i].querySelector('.mobile-description__quantity'); let buyBtnMobile = offersMobileListItems[i].querySelector('.mobile-buy__buy-btn'); if(buyBtnMobile === null){ }else{ buyBtnMobile.addEventListener('click', function (e) { e.preventDefault(); clearMobileTooltip(); buyBtnMobile.classList.remove('mobile-buy__buy-btn'); buyBtnMobile.classList.add('mobile-buy__buy-btn--load'); buyBtnMobile.innerHTML = `<div class="mobile-buy__buy-btn-preloader"></div>`; let cartBtnMobileMainHeader = document.querySelector('.user-mobile__shopping-cart span'); let key = encodeURIComponent(buyBtnMobile.dataset.key); let availability = buyBtnMobile.dataset.availability; //First click on buy btn send offer to server mech function sendOfferToCartMobile() { //Mechanic after click on Minus button const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('sendOfferToCartMobile ajax error'); errorBannerMobileRemove(); errorBannerMobile(); buyBtnMobile.classList.remove('mobile-buy__buy-btn--load'); buyBtnMobile.classList.add('mobile-buy__buy-btn'); buyBtnMobile.innerHTML = ``; }else{ const response = xhr.response; //Hidding mechanic of fast buy & buy btn let parentBuyBlockMobile = buyBtnMobile.parentElement; let currentFastBtn = parentBuyBlockMobile.querySelector('.mobile-buy__fast-buy-btn'); if(currentFastBtn){ // debugger; currentFastBtn.style.display = 'none'; buyBtnMobile.classList.remove('mobile-buy__buy-btn--load'); buyBtnMobile.classList.add('mobile-buy__buy-btn'); buyBtnMobile.innerHTML = ` `; buyBtnMobile.style.display = 'none'; //dynamic data from cart + update counters let countFromCart = response.count; cartBtnMobileMainHeader.innerText = countFromCart; //Add quantity btns instead buy btn let quantityParent = document.createElement('div'); quantityParent.classList.add('mobile-buy-quantity'); let quantityCustomParent = document.createElement('div'); quantityCustomParent.classList.add('mobile-buy-quantity--custom'); quantityParent.innerHTML = ` <div class="mobile-buy-quantity__btn-minus" data-key="${key}"></div> <input class="mobile-buy-quantity__default-input" placeholder="1"> <div class="mobile-buy-quantity__btn-plus" data-key="${key}"></div> `; quantityCustomParent.innerHTML = ` <div class="mobile-buy-quantity__back-btn"></div> <div class="mobile-buy-quantity__custom-input-wrapper"> <input class="mobile-buy-quantity__custom-input" pattern="[0-9]*" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a class="mobile-buy-quantity__buy-btn"></a> </div> `; parentBuyBlockMobile.appendChild(quantityParent); parentBuyBlockMobile.appendChild(quantityCustomParent); //Add tooltip mobileBuyTooltip(); stickyHeaderMobileCartCountUpdate(); trackCartCountMobile(); //after buy mechs let afterBuyMinusButton = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__btn-minus'); let afterBuyPlusButton = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__btn-plus'); let afterBuyInput = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__default-input'); let afterBuyCustomInput = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__custom-input'); const afterBuyQuantityBuyButton = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__buy-btn'); function checkAvailabilityBeforeClickMobile(){ let afterBuyInput = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__default-input'); let afterBuyInputPlaceholder = afterBuyInput.placeholder; if(Number(afterBuyInputPlaceholder) >= Number(availability)){ // console.warn('afterBuyInputPlaceholder >= availability'); offersMobileQuantityBlock.classList.add('mobile-description__quantity--alert'); function offerCardAvailableSignAlertDisapearMobile() { offersMobileQuantityBlock.classList.remove('mobile-description__quantity--alert'); } setTimeout(offerCardAvailableSignAlertDisapearMobile, 7000); afterBuyPlusButton.classList.remove('mobile-buy-quantity__btn-plus'); afterBuyPlusButton.classList.add('mobile-buy-quantity__btn-plus--disable'); afterBuyInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClickMobile(); //Minus button mech afterBuyMinusButton.addEventListener('click', function () { if (afterBuyInput.placeholder == '1') { const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); } else { const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnMobileMainHeader.innerText = countFromCart; stickyHeaderMobileCartCountUpdate(); trackCartCountMobile(); //Quantity + - hidden quantityParent.remove(); quantityCustomParent.remove(); //Fast buy & buy btn onn currentFastBtn.style.display = 'block'; buyBtnMobile.style.display = 'block'; } } xhr.send(params); }else { const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); } else { const response = xhr.response; let countFromCart = response.count; cartBtnMobileMainHeader.innerText = countFromCart; stickyHeaderMobileCartCountUpdate(); trackCartCountMobile(); --afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; afterBuyPlusButton.classList.remove('mobile-buy-quantity__btn-plus--disable'); afterBuyPlusButton.classList.add('mobile-buy-quantity__btn-plus'); afterBuyInput.style.pointerEvents = 'auto'; } } xhr.send(params); } }); //Plus button mech afterBuyPlusButton.addEventListener('click', function () { // console.log('key in afterBuyPlus mech'); const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); } else { const response = xhr.response; let countFromCart = response.count; cartBtnMobileMainHeader.innerText = countFromCart; stickyHeaderMobileCartCountUpdate(); trackCartCountMobile(); ++afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; checkAvailabilityBeforeClickMobile(); } } xhr.send(params); }); //input mech afterBuyInput.addEventListener('click', function(){ quantityParent.style.display = 'none'; quantityCustomParent.style.display = 'flex'; const afterBuyCustomQuantityInputMobile = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__custom-input'); const afterBuyCustomQuantityBackBtnMobile = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__back-btn'); localStorage.setItem('mobileCustomQuantityInputValue', afterBuyInput.placeholder); afterBuyCustomQuantityInputMobile.focus(); afterBuyCustomQuantityInputMobile.addEventListener('input', function(e){ const afterBuyCustomQuantityInputMobileValue = afterBuyCustomQuantityInputMobile.value; if(Number(afterBuyCustomQuantityInputMobile.value) < Number(availability)){ // console.warn(`МОБИЛЬНЫЙ КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); localStorage.setItem('mobileCustomQuantityInputValue', afterBuyCustomQuantityInputMobileValue); }else if(Number(afterBuyCustomQuantityInputMobile.value) > Number(availability)){ // console.warn(`МОБИЛЬНЫЙ КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); offersMobileQuantityBlock.classList.add('mobile-description__quantity--alert'); function offerCardAvailableSignAlertDisapearMobile() { offersMobileQuantityBlock.classList.remove('mobile-description__quantity--alert'); } setTimeout(offerCardAvailableSignAlertDisapearMobile, 7000); afterBuyCustomQuantityInputMobile.value = availability; localStorage.setItem('mobileCustomQuantityInputValue', availability); }else if(typeof availability === 'string'){ localStorage.setItem('mobileCustomQuantityInputValue', afterBuyCustomQuantityInputMobileValue); } }); afterBuyCustomQuantityBackBtnMobile.addEventListener('click', function(){ quantityParent.style.display = 'flex'; quantityCustomParent.style.display = 'none'; }); }); afterBuyQuantityBuyButton.addEventListener('click', function(e){ e.preventDefault(); let mobileCustomQuantityInputValue = localStorage.getItem('mobileCustomQuantityInputValue'); if(mobileCustomQuantityInputValue == ''){ console.warn('mobileCustomQuantityInputValue === empty string'); }else{ // console.warn('mobileCustomQuantityInputValue'); // console.warn(mobileCustomQuantityInputValue); let thisBtn = this; thisBtn.classList.remove('mobile-buy-quantity__buy-btn'); thisBtn.classList.add('mobile-buy-quantity__buy-btn--load'); thisBtn.innerHTML = `<div class="mobile-buy__buy-btn-preloader"></div>`; function sendOfferToCartMobileCustomQuamnity(){ const params = new URLSearchParams(); params.set('id', key); params.append('qty', mobileCustomQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('modalCustomQuantityBuyButtonMech ajax error'); } else { // console.warn('modalCustomQuantityBuyButtonMech ajax SUCCESS'); thisBtn.classList.remove('mobile-buy-quantity__buy-btn--load'); thisBtn.classList.add('mobile-buy-quantity__buy-btn'); thisBtn.innerHTML = ` `; // dynamic data from cart const response = xhr.response; let countFromCart = response.count; cartBtnMobileMainHeader.innerText = countFromCart; stickyHeaderMobileCartCountUpdate(); trackCartCountMobile(); afterBuyInput.placeholder = mobileCustomQuantityInputValue; quantityParent.style.display = 'flex'; quantityCustomParent.style.display = 'none'; checkAvailabilityBeforeClickMobile(); } } xhr.send(params); } setTimeout(sendOfferToCartMobileCustomQuamnity, 300); } }); }else{ let currentFastBtnSuccess = parentBuyBlockMobile.querySelector('.mobile-buy__fast-buy-btn--success'); if(currentFastBtnSuccess){ // debugger; currentFastBtnSuccess.style.display = 'none'; buyBtnMobile.classList.remove('mobile-buy__buy-btn--load'); buyBtnMobile.classList.add('mobile-buy__buy-btn'); buyBtnMobile.innerHTML = ` `; buyBtnMobile.style.display = 'none'; //dynamic data from cart + update counters let countFromCart = response.count; cartBtnMobileMainHeader.innerText = countFromCart; //Add quantity btns instead buy btn let quantityParent = document.createElement('div'); quantityParent.classList.add('mobile-buy-quantity'); let quantityCustomParent = document.createElement('div'); quantityCustomParent.classList.add('mobile-buy-quantity--custom'); quantityParent.innerHTML = ` <div class="mobile-buy-quantity__btn-minus" data-key="${key}"></div> <input class="mobile-buy-quantity__default-input" placeholder="1"> <div class="mobile-buy-quantity__btn-plus" data-key="${key}"></div> `; quantityCustomParent.innerHTML = ` <div class="mobile-buy-quantity__back-btn"></div> <div class="mobile-buy-quantity__custom-input-wrapper"> <input class="mobile-buy-quantity__custom-input" pattern="[0-9]*" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a class="mobile-buy-quantity__buy-btn"></a> </div> `; parentBuyBlockMobile.appendChild(quantityParent); parentBuyBlockMobile.appendChild(quantityCustomParent); //Add tooltip mobileBuyTooltip(); stickyHeaderMobileCartCountUpdate(); trackCartCountMobile(); //after buy mechs let afterBuyMinusButton = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__btn-minus'); let afterBuyPlusButton = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__btn-plus'); let afterBuyInput = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__default-input'); let afterBuyCustomInput = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__custom-input'); const afterBuyQuantityBuyButton = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__buy-btn'); function checkAvailabilityBeforeClickMobile(){ let afterBuyInput = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__default-input'); let afterBuyInputPlaceholder = afterBuyInput.placeholder; if(Number(afterBuyInputPlaceholder) >= Number(availability)){ // console.warn('afterBuyInputPlaceholder >= availability'); offersMobileQuantityBlock.classList.add('mobile-description__quantity--alert'); function offerCardAvailableSignAlertDisapearMobile() { offersMobileQuantityBlock.classList.remove('mobile-description__quantity--alert'); } setTimeout(offerCardAvailableSignAlertDisapearMobile, 7000); afterBuyPlusButton.classList.remove('mobile-buy-quantity__btn-plus'); afterBuyPlusButton.classList.add('mobile-buy-quantity__btn-plus--disable'); afterBuyInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClickMobile(); //Minus button mech afterBuyMinusButton.addEventListener('click', function () { if (afterBuyInput.placeholder == '1') { const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); } else { const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnMobileMainHeader.innerText = countFromCart; stickyHeaderMobileCartCountUpdate(); trackCartCountMobile(); //Quantity + - hidden quantityParent.remove(); quantityCustomParent.remove(); //Fast buy & buy btn onn currentFastBtnSuccess.style.display = 'block'; buyBtnMobile.style.display = 'block'; } } xhr.send(params); }else { const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); } else { const response = xhr.response; let countFromCart = response.count; cartBtnMobileMainHeader.innerText = countFromCart; stickyHeaderMobileCartCountUpdate(); trackCartCountMobile(); --afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; afterBuyPlusButton.classList.remove('mobile-buy-quantity__btn-plus--disable'); afterBuyPlusButton.classList.add('mobile-buy-quantity__btn-plus'); afterBuyInput.style.pointerEvents = 'auto'; } } xhr.send(params); } }); //Plus button mech afterBuyPlusButton.addEventListener('click', function () { // console.log('key in afterBuyPlus mech'); const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); } else { const response = xhr.response; let countFromCart = response.count; cartBtnMobileMainHeader.innerText = countFromCart; stickyHeaderMobileCartCountUpdate(); trackCartCountMobile(); ++afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; checkAvailabilityBeforeClickMobile(); } } xhr.send(params); }); //input mech afterBuyInput.addEventListener('click', function(){ quantityParent.style.display = 'none'; quantityCustomParent.style.display = 'flex'; const afterBuyCustomQuantityInputMobile = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__custom-input'); const afterBuyCustomQuantityBackBtnMobile = parentBuyBlockMobile.querySelector('.mobile-buy-quantity__back-btn'); localStorage.setItem('mobileCustomQuantityInputValue', afterBuyInput.placeholder); afterBuyCustomQuantityInputMobile.focus(); afterBuyCustomQuantityInputMobile.addEventListener('input', function(e){ const afterBuyCustomQuantityInputMobileValue = afterBuyCustomQuantityInputMobile.value; if(Number(afterBuyCustomQuantityInputMobile.value) < Number(availability)){ // console.warn(`МОБИЛЬНЫЙ КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); localStorage.setItem('mobileCustomQuantityInputValue', afterBuyCustomQuantityInputMobileValue); }else if(Number(afterBuyCustomQuantityInputMobile.value) > Number(availability)){ // console.warn(`МОБИЛЬНЫЙ КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); offersMobileQuantityBlock.classList.add('mobile-description__quantity--alert'); function offerCardAvailableSignAlertDisapearMobile() { offersMobileQuantityBlock.classList.remove('mobile-description__quantity--alert'); } setTimeout(offerCardAvailableSignAlertDisapearMobile, 7000); afterBuyCustomQuantityInputMobile.value = availability; localStorage.setItem('mobileCustomQuantityInputValue', availability); }else if(typeof availability === 'string'){ localStorage.setItem('mobileCustomQuantityInputValue', afterBuyCustomQuantityInputMobileValue); } }); afterBuyCustomQuantityBackBtnMobile.addEventListener('click', function(){ quantityParent.style.display = 'flex'; quantityCustomParent.style.display = 'none'; }); }); afterBuyQuantityBuyButton.addEventListener('click', function(e){ e.preventDefault(); let mobileCustomQuantityInputValue = localStorage.getItem('mobileCustomQuantityInputValue'); if(mobileCustomQuantityInputValue == ''){ console.warn('mobileCustomQuantityInputValue === empty string'); }else{ // console.warn('mobileCustomQuantityInputValue'); // console.warn(mobileCustomQuantityInputValue); let thisBtn = this; thisBtn.classList.remove('mobile-buy-quantity__buy-btn'); thisBtn.classList.add('mobile-buy-quantity__buy-btn--load'); thisBtn.innerHTML = `<div class="mobile-buy__buy-btn-preloader"></div>`; function sendOfferToCartMobileCustomQuamnity(){ const params = new URLSearchParams(); params.set('id', key); params.append('qty', mobileCustomQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('modalCustomQuantityBuyButtonMech ajax error'); } else { // console.warn('modalCustomQuantityBuyButtonMech ajax SUCCESS'); thisBtn.classList.remove('mobile-buy-quantity__buy-btn--load'); thisBtn.classList.add('mobile-buy-quantity__buy-btn'); thisBtn.innerHTML = ` `; // dynamic data from cart const response = xhr.response; let countFromCart = response.count; cartBtnMobileMainHeader.innerText = countFromCart; stickyHeaderMobileCartCountUpdate(); trackCartCountMobile(); afterBuyInput.placeholder = mobileCustomQuantityInputValue; quantityParent.style.display = 'flex'; quantityCustomParent.style.display = 'none'; checkAvailabilityBeforeClickMobile(); } } xhr.send(params); } setTimeout(sendOfferToCartMobileCustomQuamnity, 300); } }); } } } } xhr.send(params); } setTimeout(sendOfferToCartMobile, 400); }); } } } } offerCardMobileBuyButtonMech(); function mobileBuyTooltip(){ let buyTooltip = document.createElement('div'); let body = document.querySelector('body'); buyTooltip.classList.add('mobile-buy__buy-btn-tooltip') buyTooltip.innerHTML = ` <a href="/cart"> <div class="mobile-buy__buy-btn-tooltip-wrapper"> Товар успешно добавлен в корзину <span>Нажмите, чтобы перейти</span> </div> </a> ` body.appendChild(buyTooltip); function mobileBuyTooltipSmoothAppearance(){ buyTooltip.style.top = '0'; } function mobileBuyTooltipCloseToTimer(){ buyTooltip.style.top = '-150px'; } window.addEventListener('scroll', function(e){ let scrollPos = window.scrollY; // console.log(scrollPos); if (scrollPos < 200) { buyTooltip.style.top = '-150px'; } }); setTimeout(mobileBuyTooltipSmoothAppearance, 300) setTimeout(mobileBuyTooltipCloseToTimer, 10000) } function clearMobileTooltip() { let mobileTooltip = document.querySelectorAll('.mobile-buy__buy-btn-tooltip'); if (mobileTooltip === null) { // console.log('no tooltip on the page'); } else { mobileTooltip.forEach(item => { item.remove(); }); } } //Fast buy buttons function offerCardDesktopFastBuy(){ let fastBuyBtns = document.querySelectorAll('.desktop-buy__fast-buy-btn'); let body = document.querySelector('body'); if (fastBuyBtns === null) { }else { for (let i = 0; i < fastBuyBtns.length; i++){ fastBuyBtns[i].addEventListener('click', function fastBuyFetchDesktop(e){ e.preventDefault(); const thisBtn = this; let thisBtnKey = thisBtn.dataset.key; let thisBtnTooltip = thisBtn.querySelector('.desktop-buy__fast-buy-btn-tooltip'); // console.log(thisBtnKey); let requestUrl = `/form/render/3?key=${thisBtnKey}`; function fetchingFastForm(){ const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { const response = JSON.parse(xhr.response); let responseFormBlock = document.createElement("div"); responseFormBlock.innerHTML = response.html; responseFormBlock.classList.add('fast-buy-form__wrapper'); body.after(responseFormBlock); responseFormBlock.style.display = 'flex'; body.style.overflow = 'hidden'; //close current active fast buy form let currentCloseBtn = responseFormBlock.querySelector('.fast-buy-form__close'); currentCloseBtn.addEventListener('click', function(){ responseFormBlock.style.display = 'none'; responseFormBlock.remove(); body.style.overflow = 'visible'; }); sendQuickOrderForm(responseFormBlock); } } xhr.open('get', requestUrl); xhr.send(); } fetchingFastForm(); function sendQuickOrderForm(responseFormBlock) { let currentFastBtn = responseFormBlock.querySelector('.fast-buy-form__button button'); let quickOrderForm = responseFormBlock.querySelector('.fast-buy-form'); let body = document.querySelector('body'); let requestUrl = quickOrderForm.getAttribute('action'); currentFastBtn.addEventListener('click', function(e){ e.preventDefault(); currentFastBtn.innerHTML = `Отправить заявку на покупку <div class='fast-buy-form__preloader'></div>` function inputsValidation(){ let wishInput = responseFormBlock.querySelector('#send-form-3-textarea-25'); let nameInput = responseFormBlock.querySelector('#send-form-3-text-17'); let nameInputValue = nameInput.value; let emailInput = responseFormBlock.querySelector('#send-form-3-email-18'); let emailInputValue = emailInput.value; let numberInput = responseFormBlock.querySelector('#send-form-3-phone-19'); let numberInputValue = numberInput.value; //проверка поля ФИО //паттерн для имени - только английские и русские буквы + символ "-" let namePattern = /^[a-zA-Zа-яА-ЯёЁ\s\-]+$/; if(namePattern.test(nameInputValue)){ console.log('input valid'); }else{ nameInput.style.border = '2px solid #F73D34'; nameInput.value = ''; nameInput.placeholder = 'Недопустимые символы в поле ввода!'; function delayNameInputRefresh(){ nameInput.style.border = '1px solid #174F82'; nameInput.placeholder = 'Введите свое ФИО'; } nameInput.addEventListener('click', function(){ delayNameInputRefresh(); }); setTimeout(delayNameInputRefresh, 7070); } //проверка поля email let mailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if(mailPattern.test(emailInputValue)){ console.log('input valid'); }else{ emailInput.style.border = '2px solid #F73D34'; emailInput.value = ''; emailInput.placeholder = 'Неверно введен email !'; function delayMailInputRefresh(){ emailInput.style.border = '1px solid #174F82'; emailInput.placeholder = 'Введите Ваш электронный адрес'; } emailInput.addEventListener('click', function(){ delayMailInputRefresh(); }); setTimeout(delayMailInputRefresh, 7070); } //проверка поля телефон if(numberInputValue !== ''){ let numberPattern = /^[\d\(\)\-\s]+$/; if(numberPattern.test(numberInputValue)){ console.log('input valid'); }else{ numberInput.style.border = '2px solid #F73D34'; numberInput.value = ''; numberInput.placeholder = 'Недопустимые символы в поле ввода!'; function delayNumberInputRefresh(){ numberInput.style.border = '1px solid #174F82'; numberInput.placeholder = '8 (XXX) XX-XX-XXXX'; } setTimeout(delayNumberInputRefresh, 7070); } } } inputsValidation() function sendQuickFormDelay(){ const xhr = new XMLHttpRequest(); xhr.open('POST', requestUrl); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); var formData = new FormData(quickOrderForm); console.log(formData); xhr.onreadystatechange = function() { const response = xhr.responseText; if (this.readyState == 4 && this.status == 200) { //Запрос Успешно отправлен ✓ currentFastBtn.innerHTML = `Ваш Запрос Успешно отправлен ✓`; currentFastBtn.style.boxShadow = 'none'; currentFastBtn.style.pointerEvents = 'none'; thisBtn.classList.remove('desktop-buy__fast-buy-btn'); thisBtn.classList.add('desktop-buy__fast-buy-btn--success'); thisBtn.removeEventListener('click', fastBuyFetchDesktop); thisBtn.removeAttribute('href'); thisBtnTooltip.style.width = '80px'; thisBtnTooltip.innerHTML = `Запрос отправлен` function delayFormHide(){ responseFormBlock.remove(); body.style.overflow = 'visible'; } setTimeout(delayFormHide, 2000); }else{ //ошибка // console.warn('ajax error'); currentFastBtn.innerHTML = `Отправить заявку на покупку` } // console.log(response); } xhr.send(formData); } setTimeout(sendQuickFormDelay, 1000); }); } }); } } } offerCardDesktopFastBuy(); //Fast buy`s tooltip function offerCardDesktopFastBuyTooltipMech(){ let fastBuyBtns = document.querySelectorAll('.desktop-buy__fast-buy-btn'); if(fastBuyBtns === null){ }else{ fastBuyBtns.forEach(item => { item.innerHTML = `<div class="desktop-buy__fast-buy-btn-tooltip">Быстрая покупка</div>`; let fastBuyTooltip = item.querySelector('.desktop-buy__fast-buy-btn-tooltip'); item.addEventListener('mouseover', function() { fastBuyTooltip.style.visibility = 'visible'; fastBuyTooltip.style.opacity = '1'; }) item.addEventListener('mouseout', function() { fastBuyTooltip.style.visibility = 'hidden'; fastBuyTooltip.style.opacity = '0'; }) }) } } offerCardDesktopFastBuyTooltipMech(); function offerCardMobileFastBuy(){ let fastBuyBtnsMobile = document.querySelectorAll('.mobile-buy__fast-buy-btn'); let body = document.querySelector('body'); if (fastBuyBtnsMobile === null) { }else{ for(let i = 0; i < fastBuyBtnsMobile.length; i++){ fastBuyBtnsMobile[i].addEventListener('click', function fastBuyFetchMobile(e){ e.preventDefault(); const thisBtn = this; let thisBtnKey = thisBtn.dataset.key; // console.log(thisBtnKey); let requestUrl = `/form/render/3?key=${thisBtnKey}`; function fetchingFastForm(){ const xhr = new XMLHttpRequest(); xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { const response = JSON.parse(xhr.response); let responseFormBlock = document.createElement("div"); responseFormBlock.innerHTML = response.html; responseFormBlock.classList.add('fast-buy-form__wrapper'); thisBtn.after(responseFormBlock); responseFormBlock.style.display = 'flex'; body.style.overflow = 'hidden'; //close current active fast buy form let currentCloseBtn = responseFormBlock.querySelector('.fast-buy-form__close'); currentCloseBtn.addEventListener('click', function(){ responseFormBlock.style.display = 'none'; responseFormBlock.remove(); body.style.overflow = 'visible'; }); sendQuickOrderFormMobile(responseFormBlock); } } xhr.open('get', requestUrl); xhr.send(); } fetchingFastForm(); function sendQuickOrderFormMobile(responseFormBlock) { let currentFastBtn = responseFormBlock.querySelector('.fast-buy-form__button button'); let quickOrderForm = responseFormBlock.querySelector('.fast-buy-form'); let body = document.querySelector('body'); let requestUrl = quickOrderForm.getAttribute('action'); currentFastBtn.addEventListener('click', function(e){ e.preventDefault(); currentFastBtn.innerHTML = `Отправить заявку на покупку <div class='fast-buy-form__mobile-preloader'></div>` //console.log(requestUrl); function inputsValidation(){ let wishInput = responseFormBlock.querySelector('#send-form-3-textarea-25'); let nameInput = responseFormBlock.querySelector('#send-form-3-text-17'); let nameInputValue = nameInput.value; let emailInput = responseFormBlock.querySelector('#send-form-3-email-18'); let emailInputValue = emailInput.value; let numberInput = responseFormBlock.querySelector('#send-form-3-phone-19'); let numberInputValue = numberInput.value; //проверка поля ФИО //паттерн для имени - только английские и русские буквы + символ "-" let namePattern = /^[a-zA-Zа-яА-ЯёЁ\s\-]+$/; if(namePattern.test(nameInputValue)){ console.log('input valid'); }else{ nameInput.style.border = '2px solid #F73D34'; nameInput.value = ''; nameInput.placeholder = 'Недопустимые символы в поле ввода!'; function delayNameInputRefresh(){ nameInput.style.border = '1px solid #174F82'; nameInput.placeholder = 'Введите свое ФИО'; } setTimeout(delayNameInputRefresh, 3030); } //проверка поля email let mailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if(mailPattern.test(emailInputValue)){ console.log('input valid'); }else{ emailInput.style.border = '2px solid #F73D34'; emailInput.value = ''; emailInput.placeholder = 'Неверно введен email !'; function delayMailInputRefresh(){ emailInput.style.border = '1px solid #174F82'; emailInput.placeholder = 'Введите Ваш электронный адрес'; } setTimeout(delayMailInputRefresh, 3030); } //проверка поля телефон if(numberInputValue !== ''){ let numberPattern = /^[\d\(\)\-\s]+$/; if(numberPattern.test(numberInputValue)){ console.log('input valid'); }else{ numberInput.style.border = '2px solid #F73D34'; numberInput.value = ''; numberInput.placeholder = 'Недопустимые символы в поле ввода!'; function delayNumberInputRefresh(){ numberInput.style.border = '1px solid #174F82'; numberInput.placeholder = '8 (XXX) XX-XX-XXXX'; } setTimeout(delayNumberInputRefresh, 3030); } } } inputsValidation() function sendQuickFormDelay(){ const xhr = new XMLHttpRequest(); xhr.open('POST', requestUrl); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); var formData = new FormData(quickOrderForm); console.log(formData); xhr.onreadystatechange = function() { const response = xhr.responseText; if (this.readyState == 4 && this.status == 200) { //Запрос Успешно отправлен ✓ currentFastBtn.innerHTML = `Ваш Запрос Успешно отправлен ✓`; currentFastBtn.style.boxShadow = 'none'; currentFastBtn.style.pointerEvents = 'none'; thisBtn.classList.remove('mobile-buy__fast-buy-btn'); thisBtn.classList.add('mobile-buy__fast-buy-btn--success'); thisBtn.removeEventListener('click', fastBuyFetchMobile); thisBtn.removeAttribute('href'); function delayFormHide(){ responseFormBlock.remove(); body.style.overflow = 'visible'; } setTimeout(delayFormHide, 2000); }else{ //ошибка // console.warn('ajax error'); currentFastBtn.innerHTML = `Отправить заявку на покупку` } console.log(response); } xhr.send(formData); } setTimeout(sendQuickFormDelay, 1000); }); } }); } } } offerCardMobileFastBuy(); function offerCardDesktopInfoOpen(){ let desktopCardItem = document.querySelectorAll('.desktop-card-item'); if (desktopCardItem === null) { // console.log("desktopCardItem left HTML"); } else { for(let i = 0; i < desktopCardItem.length; i++){ let desktopProp = desktopCardItem[i].querySelector(".desktop-properties"); let desktopInfoBlock = desktopCardItem[i].querySelector(".desktop-info"); let desktopInfoBlockClose = desktopCardItem[i].querySelector(".desktop-info__items-close"); if(desktopInfoBlockClose === null){ if (desktopProp === null || desktopInfoBlock === null) { // console.log("offerCard components left html"); } else { desktopProp.addEventListener("click", function() { desktopInfoBlock.classList.toggle("desktop-info--on"); }); } }else{ if (desktopProp === null || desktopInfoBlock === null) { // console.log("offerCard components left html"); } else { desktopProp.addEventListener("click", function() { desktopInfoBlock.classList.toggle("desktop-info--on"); }); desktopInfoBlockClose.addEventListener("click", function() { desktopInfoBlock.classList.remove("desktop-info--on"); }); } } } } } offerCardDesktopInfoOpen(); function offerCardDesktopOpen(){ let offerCardDesktop = document.querySelectorAll('.offer-card-desktop'); if (offerCardDesktop === null) { // console.log("offerCardDesktop left HTML"); }else{ for(let i = 0; i < offerCardDesktop.length; i++){ let offerCardDesktopOpenBtn = offerCardDesktop[i].querySelector('.short-panel-desktop__open'); let fullDesktopCard = offerCardDesktop[i].querySelector('.full-desktop-card'); let fullDesktopCloseBtn = offerCardDesktop[i].querySelector('.desktop-filter__close'); let offerCardStart = offerCardDesktop[i].querySelector('.short-options-desktop'); if (offerCardDesktopOpenBtn === null || fullDesktopCard === null || fullDesktopCloseBtn === null) { // console.log("offerCardDesktop components left html"); } else { offerCardDesktopOpenBtn.addEventListener('click', function() { fullDesktopCard.classList.add('full-desktop-card--on'); offerCardDesktopOpenBtn.style.visibility = 'hidden'; }); fullDesktopCloseBtn.addEventListener('click', function() { fullDesktopCard.classList.remove('full-desktop-card--on'); offerCardDesktopOpenBtn.style.visibility = 'visible'; }); } } } } //Separator function hideFirstSeparatorOnDesktop(){ let firstSeparator = document.querySelector('.offer-card-separator'); if (firstSeparator === null) { // сonsole.log("firstSeparator left HTML"); }else{ firstSeparator.style.display = 'none'; } } hideFirstSeparatorOnDesktop(); // Desktop card offer more button function desktopCardMoreBtn(){ let desktopCards = document.querySelectorAll('.short-card-description'); if(desktopCards === null){ // console.log('no offers on page'); }else{ for(let i = 0; i < desktopCards.length;i++){ desktopCards[i].addEventListener('mouseover', function(e){ e.preventDefault(); let currentCard = this; let currentBtn = currentCard.querySelector('.short-card-description__more'); if(currentBtn === null){ }else{ currentBtn.classList.add('short-card-description__more--hover'); } }); desktopCards[i].addEventListener('mouseout', function(e){ e.preventDefault(); let currentCard = this; let currentBtn = currentCard.querySelector('.short-card-description__more'); if(currentBtn === null){ }else{ currentBtn.classList.remove('short-card-description__more--hover'); } }); } } } desktopCardMoreBtn(); //fix for ios - disable auto zoom on inputs fields + iOS telephone blue mark FIX function changeMetaTagOnPage(){ let viewport = document.querySelector("meta[name=viewport]"); if(viewport === null){ }else{ viewport.setAttribute('content', 'width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0'); //iOS phone FIX let meta = document.createElement('meta'); let mobilePhoneBlock = document.querySelector('.right-panel__info'); if(mobilePhoneBlock === null){ }else{ mobilePhoneBlock.innerHTML = `+7 (495) ‍649 60 60`; meta.name = "format-detection"; meta.content = "telephone=no"; document.getElementsByTagName('head')[0].appendChild(meta); } } } changeMetaTagOnPage(); //Favorite TO EMAIL function favoriteToEmailForm() { const favoriteForm = document.querySelectorAll('.favorite-to-mail-form'); if (favoriteForm.length === 0) return; const emailPattern = /^(([^<>()[\]\.,;:\s@\"]+(\.[^<>()[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i; for (let i = 0; i < favoriteForm.length; i++) { const favoriteFormInput = favoriteForm[i].querySelector('.favorite-to-mail-form__input'); const favoriteFormButton = favoriteForm[i].querySelector('.favorite-to-mail-form__button'); const favoriteFormHelper = favoriteForm[i].querySelector('.favorite-to-mail-form__helper'); const body = document.querySelector('body'); favoriteFormButton.addEventListener('click', function favoriteFormButtonClick(e) { const favoriteFromInputValue = favoriteFormInput.value; if (emailPattern.test(favoriteFromInputValue)) { localStorage.setItem('favoriteFromInputValue', favoriteFromInputValue); favoriteToEmailFormSend(); } else { favoriteFormInput.classList.add('favorite-to-mail-form__input--alert'); favoriteFormHelper.classList.add('favorite-to-mail-form__helper--alert'); favoriteFormHelper.innerText = 'Проверьте правильность адреса почты'; function favoriteFromHelperReset() { favoriteFormInput.classList.remove('favorite-to-mail-form__input--alert'); favoriteFormHelper.classList.remove('favorite-to-mail-form__helper--alert'); favoriteFormHelper.innerText = 'Отправить список Избранного на почту'; } setTimeout(favoriteFromHelperReset, 4000); } function favoriteToEmailFormSend() { document.body.style.cursor = 'wait'; favoriteFormButton.style.pointerEvents = 'none'; const favoriteFromInputValue = localStorage.getItem('favoriteFromInputValue'); const params = new URLSearchParams(); params.set('email', favoriteFromInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/send'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('favoriteToEmailFormSend ajax error'); favoriteFormHelper.innerText = 'Ошибка, попробуйте позже :)'; } else { const response = xhr.response; // generate modal let favoriteFormModal = document.createElement('div'); favoriteFormModal.classList.add('favorite-to-mail-form-modal' , 'open'); favoriteFormModal.innerHTML = ` <div class="favorite-to-mail-form-modal__blur"></div> <div class="favorite-to-mail-form-modal__wrapper open-animation"> <div class="favorite-to-mail-form-modal__close"></div> <div class="favorite-to-mail-form-modal__pic"></div> <div class="favorite-to-mail-form-modal__subtitle"> Список Избранного успешно отправлен на почту ${favoriteFromInputValue} </div> <div class="favorite-to-mail-form-modal__button">Отлично!</div> </div> `; body.appendChild(favoriteFormModal); body.classList.add('page-body__no-scroll'); document.body.style.cursor = 'default'; favoriteFormButton.style.pointerEvents = 'auto'; const favoriteFormModalButton = favoriteFormModal.querySelector('.favorite-to-mail-form-modal__button'); const favoriteFormModalClose = favoriteFormModal.querySelector('.favorite-to-mail-form-modal__close'); const favoriteFormModalBlur = favoriteFormModal.querySelector('.favorite-to-mail-form-modal__blur'); const favoriteFormModalWrapper = favoriteFormModal.querySelector('.favorite-to-mail-form-modal__wrapper'); function closeModal() { favoriteFormModalWrapper.classList.remove('open-animation'); favoriteFormModalWrapper.classList.add('close-animation'); setTimeout(() => { favoriteFormModal.remove(); body.classList.remove('page-body__no-scroll'); }, 300); } favoriteFormModalButton.addEventListener('click', closeModal); favoriteFormModalClose.addEventListener('click', closeModal); favoriteFormModalBlur.addEventListener('click', closeModal); favoriteFormButton.removeEventListener('click', favoriteFormButtonClick); favoriteFormHelper.innerText = `Список успешно отправлен`; } } xhr.send(params); } }); } } favoriteToEmailForm(); //OFFERS catalog Sort by Price DESKTOP function offersCatalogSortByPriceMechDesktop(){ const offerCardPricesContainer = document.querySelectorAll('.full-desktop-card') if(offerCardPricesContainer === null){ }else{ for(let i = 0; i < offerCardPricesContainer.length; i++){ const sortByPriceAllPrices = offerCardPricesContainer[i].querySelectorAll('.desktop-card-item'); const sortByPriceAllPricesParent = offerCardPricesContainer[i].querySelector('.full-desktop-card__list'); const sortByPriceBtnMain = offerCardPricesContainer[i].querySelector('.offers-desktop-filter-price'); const sortByPriceList = offerCardPricesContainer[i].querySelector('.offers-desktop-filter-price__list'); const sortByPriceItems = sortByPriceList.querySelectorAll('.offers-desktop-filter-price__item'); const sortByPriceSortBtnDefault = sortByPriceItems[0]; const sortByPriceSortBtnAscending = sortByPriceItems[1]; const sortByPriceSortBtnDescending = sortByPriceItems[2]; function offerStockRecognition(){ const offers = document.querySelectorAll('.desktop-card-item') if(offers !== null){ offers.forEach(item => { const showRoomStock = item.querySelector('.desktop-properties__icons--showroom'); if(item.contains(showRoomStock)){ item.classList.add('stockOfferShowRoom'); }else{ item.classList.add('stockOfferDefault'); } }) } } offerStockRecognition(); function refreshActiveStatesOnFilterItems(){ sortByPriceItems.forEach(item => { item.classList.remove('offers-desktop-filter-price__item--active'); }); } sortByPriceBtnMain.addEventListener('click', function(){ sortByPriceList.classList.toggle('offers-desktop-filter-price__list--active'); sortByPriceBtnMain.classList.toggle('offers-desktop-filter-price--active'); }); //Сортировать по Умолчанию [сначала домики по возрастанию, потом обычные] function sortOffersShowRoom(){ const stockOfferShowRoom = offerCardPricesContainer[i].querySelectorAll('.stockOfferShowRoom'); const stockOfferDefault = offerCardPricesContainer[i].querySelectorAll('.stockOfferDefault'); if(stockOfferShowRoom){ const elements = Array.from(stockOfferShowRoom); const sortedElements = elements.sort((a, b) => { const aPrice = parseFloat(a.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); const bPrice = parseFloat(b.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParent.prepend(...sortedElements); } refreshActiveStatesOnFilterItems(); sortByPriceSortBtnDefault.classList.add('offers-desktop-filter-price__item--active'); } function sortOffersDefault(){ return new Promise((resolve) => { // выполнение первой функции const stockOfferDefault = offerCardPricesContainer[i].querySelectorAll('.stockOfferDefault'); if(stockOfferDefault){ const elements = Array.from(stockOfferDefault); const sortedElements = elements.sort((a, b) => { const aPrice = parseFloat(a.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); const bPrice = parseFloat(b.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParent.prepend(...sortedElements); } resolve(); }); } sortOffersDefault().then(sortOffersShowRoom); sortByPriceSortBtnDefault.addEventListener('click', function(){ sortOffersDefault().then(sortOffersShowRoom); }); //Сортировать по Убыванию ДОРОЖЕ sortByPriceSortBtnDescending.addEventListener('click', function(){ const elements = Array.from(sortByPriceAllPrices); const sortedElements = elements.sort((a, b) => { const aPrice = parseFloat(a.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); const bPrice = parseFloat(b.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); if (isNaN(aPrice)) return -1; if (isNaN(bPrice)) return 1; return aPrice - bPrice; }).reverse(); sortByPriceAllPricesParent.prepend(...sortedElements); refreshActiveStatesOnFilterItems(); sortByPriceSortBtnDescending.classList.add('offers-desktop-filter-price__item--active'); }); //Сортировать по Возрастанию ДЕШЕВЛЕ sortByPriceSortBtnAscending.addEventListener('click', function(){ const elements = Array.from(sortByPriceAllPrices); const sortedElements = elements.sort((a, b) => { const aPrice = parseFloat(a.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); const bPrice = parseFloat(b.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParent.prepend(...sortedElements); refreshActiveStatesOnFilterItems(); sortByPriceSortBtnAscending.classList.add('offers-desktop-filter-price__item--active'); }); } } } offersCatalogSortByPriceMechDesktop(); //OFFERS catalog Sort by Price MOBILE function offersCatalogSortByPriceMechMobile(){ const offerCardPricesContainer = document.querySelectorAll('.full-mobile-card'); if(offerCardPricesContainer === null){ }else{ for(let i = 0; i < offerCardPricesContainer.length; i++){ const sortByPriceAllPricesMobile = offerCardPricesContainer[i].querySelectorAll('.mobile-list-item'); const sortByPriceAllPricesParentMobile = offerCardPricesContainer[i].querySelector('.full-mobile-card__list'); const sortByPriceBtnMain = offerCardPricesContainer[i].querySelector('.offers-mobile-filter-price'); const sortByPriceList = offerCardPricesContainer[i].querySelector('.offers-mobile-filter-price__list'); const sortByPriceItems = sortByPriceList.querySelectorAll('.offers-mobile-filter-price__item'); const sortByPriceSortBtnDefault = sortByPriceItems[0]; const sortByPriceSortBtnAscending = sortByPriceItems[1]; const sortByPriceSortBtnDescending = sortByPriceItems[2]; const parentArticle = offerCardPricesContainer[i].parentElement; const openBtn = parentArticle.querySelector('.short-panel-mobile__open'); function refreshActiveStatesOnFilterItems(){ sortByPriceItems.forEach(item => { item.classList.remove('offers-mobile-filter-price__item--active') }); } function offerStockRecognition(){ const offersMobile = document.querySelectorAll('.mobile-list-item') if(offersMobile !== null){ offersMobile.forEach(item => { const showRoomStock = item.querySelector('.mobile-properties__state--showroom'); if(item.contains(showRoomStock)){ item.classList.add('stockOfferShowRoomMobile'); }else{ item.classList.add('stockOfferDefaultMobile'); } }) } } sortByPriceBtnMain.addEventListener('click', function(){ sortByPriceList.classList.toggle('offers-mobile-filter-price__list--active'); sortByPriceBtnMain.classList.toggle('offers-mobile-filter-price--active'); }); //Сортировать по Умолчанию [сначала домики по возрастанию, потом обычные] function sortOffersShowRoomMobile(){ const stockOfferShowRoom = offerCardPricesContainer[i].querySelectorAll('.stockOfferShowRoomMobile'); if(stockOfferShowRoom){ const elements = Array.from(stockOfferShowRoom); const sortedElements = elements.sort((a, b) => { const aPriceElement = a.querySelector('.mobile-buy__price'); const bPriceElement = b.querySelector('.mobile-buy__price'); const aPrice = aPriceElement && aPriceElement.textContent ? parseFloat(aPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; const bPrice = bPriceElement && bPriceElement.textContent ? parseFloat(bPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParentMobile.prepend(...sortedElements); } refreshActiveStatesOnFilterItems(); sortByPriceSortBtnDefault.classList.add('offers-mobile-filter-price__item--active'); } function sortOffersDefaultMobile(){ return new Promise((resolve) => { // выполнение первой функции const stockOfferDefault = offerCardPricesContainer[i].querySelectorAll('.stockOfferDefaultMobile'); if(stockOfferDefault){ const elements = Array.from(stockOfferDefault); const sortedElements = elements.sort((a, b) => { const aPriceElement = a.querySelector('.mobile-buy__price'); const bPriceElement = b.querySelector('.mobile-buy__price'); const aPrice = aPriceElement && aPriceElement.textContent ? parseFloat(aPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; const bPrice = bPriceElement && bPriceElement.textContent ? parseFloat(bPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParentMobile.prepend(...sortedElements); } resolve(); }); } //sort then on card openning if(openBtn){ openBtn.addEventListener('click', function(){ console.warn('open sort!'); offerStockRecognition(); setTimeout(() => { sortOffersDefaultMobile().then(sortOffersShowRoomMobile); }, 150); }) } sortByPriceSortBtnDefault.addEventListener('click', function(){ sortOffersDefaultMobile().then(sortOffersShowRoomMobile); }); //Сортировать по Убыванию ДОРОЖЕ sortByPriceSortBtnDescending.addEventListener('click', function(){ const elements = Array.from(sortByPriceAllPricesMobile); const sortedElements = elements.sort((a, b) => { const aPriceElement = a.querySelector('.mobile-buy__price'); const bPriceElement = b.querySelector('.mobile-buy__price'); const aPrice = aPriceElement && aPriceElement.textContent ? parseFloat(aPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; const bPrice = bPriceElement && bPriceElement.textContent ? parseFloat(bPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; if (isNaN(aPrice)) return -1; if (isNaN(bPrice)) return 1; return aPrice - bPrice; }).reverse(); sortByPriceAllPricesParentMobile.prepend(...sortedElements); refreshActiveStatesOnFilterItems(); sortByPriceSortBtnDescending.classList.add('offers-mobile-filter-price__item--active'); }); //Сортировать по Возрастанию ДЕШЕВЛЕ sortByPriceSortBtnAscending.addEventListener('click', function(){ const elements = Array.from(sortByPriceAllPricesMobile); const sortedElements = elements.sort((a, b) => { const aPriceElement = a.querySelector('.mobile-buy__price'); const bPriceElement = b.querySelector('.mobile-buy__price'); const aPrice = aPriceElement && aPriceElement.textContent ? parseFloat(aPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; const bPrice = bPriceElement && bPriceElement.textContent ? parseFloat(bPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParentMobile.prepend(...sortedElements); refreshActiveStatesOnFilterItems(); sortByPriceSortBtnAscending.classList.add('offers-mobile-filter-price__item--active'); }); } } } offersCatalogSortByPriceMechMobile(); //sorting in opened offer card function openedCartSortFunctions(){ const offerCardOpenned = document.querySelector('.offers-vendor-catalog-desktop__offer'); if(offerCardOpenned){ const offerCardPricesContainer = document.querySelector('.full-desktop-card--on') if(offerCardPricesContainer){ const sortByPriceAllPrices = offerCardPricesContainer.querySelectorAll('.desktop-card-item'); const sortByPriceAllPricesParent = offerCardPricesContainer.querySelector('.full-desktop-card__list'); const sortByPriceBtnMain = offerCardPricesContainer.querySelector('.offers-desktop-filter-price'); const sortByPriceList = offerCardPricesContainer.querySelector('.offers-desktop-filter-price__list'); const sortByPriceItems = sortByPriceList.querySelectorAll('.offers-desktop-filter-price__item'); const sortByPriceSortBtnDefault = sortByPriceItems[0]; const sortByPriceSortBtnDescending = sortByPriceItems[1]; const sortByPriceSortBtnAscending = sortByPriceItems[2]; const deskFilterForPad = document.querySelector('.desktop-filter'); deskFilterForPad.style.paddingRight = '5px'; function offerStockRecognition(){ const offers = document.querySelectorAll('.desktop-card-item') if(offers !== null){ offers.forEach(item => { const showRoomStock = item.querySelector('.desktop-properties__icons--showroom'); if(item.contains(showRoomStock)){ item.classList.add('stockOfferShowRoom'); }else{ item.classList.add('stockOfferDefault'); } }) } } offerStockRecognition(); function refreshActiveStatesOnFilterItems(){ sortByPriceItems.forEach(item => { item.classList.remove('offers-mobile-filter-price__item--active') }); } sortByPriceBtnMain.addEventListener('click', function(){ sortByPriceList.classList.toggle('offers-desktop-filter-price__list--active'); sortByPriceBtnMain.classList.toggle('offers-desktop-filter-price--active'); }); //Сортировать по Умолчанию [сначала домики по возрастанию, потом обычные] function sortOffersShowRoom(){ const stockOfferShowRoom = offerCardPricesContainer.querySelectorAll('.stockOfferShowRoom'); const stockOfferDefault = offerCardPricesContainer.querySelectorAll('.stockOfferDefault'); if(stockOfferShowRoom){ const elements = Array.from(stockOfferShowRoom); const sortedElements = elements.sort((a, b) => { const aPrice = parseFloat(a.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); const bPrice = parseFloat(b.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParent.prepend(...sortedElements); } refreshActiveStatesOnFilterItems(); sortByPriceSortBtnDefault.classList.add('offers-desktop-filter-price__item--active'); } function sortOffersDefault(){ return new Promise((resolve) => { // выполнение первой функции const stockOfferDefault = offerCardPricesContainer.querySelectorAll('.stockOfferDefault'); if(stockOfferDefault){ const elements = Array.from(stockOfferDefault); const sortedElements = elements.sort((a, b) => { const aPrice = parseFloat(a.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); const bPrice = parseFloat(b.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParent.prepend(...sortedElements); } resolve(); }); } sortOffersDefault().then(sortOffersShowRoom); sortByPriceSortBtnDefault.addEventListener('click', function(){ sortOffersDefault().then(sortOffersShowRoom); }); //Сортировать по Убыванию ДОРОЖЕ sortByPriceSortBtnDescending.addEventListener('click', function(){ const elements = Array.from(sortByPriceAllPrices); const sortedElements = elements.sort((a, b) => { const aPrice = parseFloat(a.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); const bPrice = parseFloat(b.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); if (isNaN(aPrice)) return -1; if (isNaN(bPrice)) return 1; return aPrice - bPrice; }).reverse(); sortByPriceAllPricesParent.prepend(...sortedElements); refreshActiveStatesOnFilterItems(); sortByPriceSortBtnDescending.classList.add('offers-desktop-filter-price__item--active'); }); //Сортировать по Возрастанию ДЕШЕВЛЕ sortByPriceSortBtnAscending.addEventListener('click', function(){ const elements = Array.from(sortByPriceAllPrices); const sortedElements = elements.sort((a, b) => { const aPrice = parseFloat(a.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); const bPrice = parseFloat(b.querySelector('.desktop-card-item__price').textContent.replaceAll(/\s/g, '')); if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParent.prepend(...sortedElements); refreshActiveStatesOnFilterItems(); sortByPriceSortBtnAscending.classList.add('offers-desktop-filter-price__item--active'); }); } } } openedCartSortFunctions(); function openedCartSortFunctionsMobile(){ const offerCardOpenned = document.querySelector('.offers-vendor-catalog-mobile'); if(offerCardOpenned){ const offerCardPricesContainer = document.querySelector('.offer-card-mobile__full'); if(offerCardPricesContainer){ console.warn('openedCartSortFunctionsMobile RUN') const sortByPriceAllPricesMobile = offerCardPricesContainer.querySelectorAll('.mobile-list-item'); const sortByPriceAllPricesParentMobile = offerCardPricesContainer.querySelector('.full-mobile-card__list'); const sortByPriceBtnMain = offerCardPricesContainer.querySelector('.offers-mobile-filter-price'); const sortByPriceList = offerCardPricesContainer.querySelector('.offers-mobile-filter-price__list'); const sortByPriceItems = sortByPriceList.querySelectorAll('.offers-mobile-filter-price__item'); const sortByPriceSortBtnDefault = sortByPriceItems[0]; const sortByPriceSortBtnAscending = sortByPriceItems[1]; const sortByPriceSortBtnDescending = sortByPriceItems[2]; const filterBlockForPad = document.querySelector('.mobile-filter'); filterBlockForPad.style.paddingRight = '0'; function refreshActiveStatesOnFilterItems(){ sortByPriceItems.forEach(item => { item.classList.remove('offers-mobile-filter-price__item--active') }); } function offerStockRecognition(){ const offersMobile = document.querySelectorAll('.mobile-list-item') if(offersMobile !== null){ offersMobile.forEach(item => { const showRoomStock = item.querySelector('.mobile-properties__state--showroom'); if(showRoomStock){ console.warn(showRoomStock); item.classList.add('stockOfferShowRoomMobile'); }else{ item.classList.add('stockOfferDefaultMobile'); } }) } } offerStockRecognition(); sortByPriceBtnMain.addEventListener('click', function(){ sortByPriceList.classList.toggle('offers-mobile-filter-price__list--active'); sortByPriceBtnMain.classList.toggle('offers-mobile-filter-price--active'); }); //Сортировать по Умолчанию [сначала домики по возрастанию, потом обычные] function sortOffersShowRoomMobile(){ const stockOfferShowRoom = offerCardPricesContainer.querySelectorAll('.stockOfferShowRoomMobile'); if(stockOfferShowRoom){ const elements = Array.from(stockOfferShowRoom); const sortedElements = elements.sort((a, b) => { const aPriceElement = a.querySelector('.mobile-buy__price'); const bPriceElement = b.querySelector('.mobile-buy__price'); const aPrice = aPriceElement && aPriceElement.textContent ? parseFloat(aPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; const bPrice = bPriceElement && bPriceElement.textContent ? parseFloat(bPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParentMobile.prepend(...sortedElements); } refreshActiveStatesOnFilterItems(); sortByPriceSortBtnDefault.classList.add('offers-mobile-filter-price__item--active'); } function sortOffersDefaultMobile(){ return new Promise((resolve) => { // выполнение первой функции const stockOfferDefault = offerCardPricesContainer.querySelectorAll('.stockOfferDefaultMobile'); if(stockOfferDefault){ const elements = Array.from(stockOfferDefault); const sortedElements = elements.sort((a, b) => { const aPriceElement = a.querySelector('.mobile-buy__price'); const bPriceElement = b.querySelector('.mobile-buy__price'); const aPrice = aPriceElement && aPriceElement.textContent ? parseFloat(aPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; const bPrice = bPriceElement && bPriceElement.textContent ? parseFloat(bPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParentMobile.prepend(...sortedElements); } resolve(); }); } sortOffersDefaultMobile().then(sortOffersShowRoomMobile); sortByPriceSortBtnDefault.addEventListener('click', function(){ sortOffersDefaultMobile().then(sortOffersShowRoomMobile); }); //Сортировать по Убыванию ДОРОЖЕ sortByPriceSortBtnDescending.addEventListener('click', function(){ const elements = Array.from(sortByPriceAllPricesMobile); const sortedElements = elements.sort((a, b) => { const aPriceElement = a.querySelector('.mobile-buy__price'); const bPriceElement = b.querySelector('.mobile-buy__price'); const aPrice = aPriceElement && aPriceElement.textContent ? parseFloat(aPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; const bPrice = bPriceElement && bPriceElement.textContent ? parseFloat(bPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; if (isNaN(aPrice)) return -1; if (isNaN(bPrice)) return 1; return aPrice - bPrice; }).reverse(); sortByPriceAllPricesParentMobile.prepend(...sortedElements); refreshActiveStatesOnFilterItems(); sortByPriceSortBtnDescending.classList.add('offers-mobile-filter-price__item--active'); }); //Сортировать по Возрастанию ДЕШЕВЛЕ sortByPriceSortBtnAscending.addEventListener('click', function(){ const elements = Array.from(sortByPriceAllPricesMobile); const sortedElements = elements.sort((a, b) => { const aPriceElement = a.querySelector('.mobile-buy__price'); const bPriceElement = b.querySelector('.mobile-buy__price'); const aPrice = aPriceElement && aPriceElement.textContent ? parseFloat(aPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; const bPrice = bPriceElement && bPriceElement.textContent ? parseFloat(bPriceElement.textContent.replaceAll(/\s/g, '')) : NaN; if (isNaN(aPrice)) return 1; if (isNaN(bPrice)) return -1; return aPrice - bPrice; }); sortByPriceAllPricesParentMobile.prepend(...sortedElements); refreshActiveStatesOnFilterItems(); sortByPriceSortBtnAscending.classList.add('offers-mobile-filter-price__item--active'); }); } } } openedCartSortFunctionsMobile(); //show-hide desktop cart counter in header/sticky-header on catalog-pages function trackCartCount(){ const cartCount = document.querySelectorAll('.user__shopping-cart span'); if(cartCount !== null){ cartCount.forEach(item =>{ if(item.innerHTML === '0') { item.style.display = 'none'; }else{ item.style.display = 'inline-block'; } }); } } trackCartCount(); //show-hide mobile cart counter in header/sticky-header on catalog-pages function trackCartCountMobile() { const cartCountMobileHeader = document.querySelector('.user-mobile__shopping-cart span'); const cartCountMobileStickyHeader = document.querySelector('.stickyHeaderCartParent span'); if(cartCountMobileHeader){ if(cartCountMobileHeader.innerHTML === '0') { cartCountMobileHeader.style.display = 'none'; cartCountMobileStickyHeader.style.display = 'none'; }else{ cartCountMobileHeader.style.display = 'inline-block'; cartCountMobileStickyHeader.style.display = 'inline-block'; } } } trackCartCountMobile(); //show-hide desktop favorite counter in header/sticky-header on catalog-pages function trackFavoriteCount(){ const favCount = document.querySelectorAll('.user__favorites span'); if(favCount !== null){ favCount.forEach(item =>{ if(item.innerHTML === '0') { item.style.display = 'none'; }else{ item.style.display = 'inline-block'; } }); } } trackFavoriteCount(); //show-hide desktop favorite counter in header/sticky-header on catalog-pages function trackFavoriteCountMobile(){ const favCountMobile = document.querySelector('.user-mobile__favorites span'); const favCountMobileSticky = document.querySelector('.stickyHeaderFavoriteParent span'); if(favCountMobile){ if(favCountMobile.innerHTML === '0') { favCountMobile.style.display = 'none'; favCountMobileSticky.style.display = 'none'; }else{ favCountMobile.style.display = 'inline-block'; favCountMobileSticky.style.display = 'inline-block'; } } } trackFavoriteCountMobile(); function offersEpcLinkTip(){ let eplLinkQuestions = document.querySelectorAll('.epc-link--tip'); if(eplLinkQuestions === null){ // console.log('no shareBtns in news on the page!'); }else { for(let i = 0; i < eplLinkQuestions.length; i++){ eplLinkQuestions[i].addEventListener('mouseover', function(){ let currentTip = this.querySelector('div'); if(currentTip){ currentTip.style.visibility = 'visible'; currentTip.style.opacity = '1'; } }); eplLinkQuestions[i].addEventListener('mouseout', function(){ let currentTip = this.querySelector('div'); if(currentTip){ currentTip.style.visibility = 'hidden'; currentTip.style.opacity = '0'; } }); } } } offersEpcLinkTip(); function offersEpcLinkTipMobile(){ let eplLinkQuestionsMobile = document.querySelectorAll('.epc-link--tip-mobile'); if(eplLinkQuestionsMobile === null){ // console.log('no shareBtns in news on the page!'); }else { for(let i = 0; i < eplLinkQuestionsMobile.length; i++){ eplLinkQuestionsMobile[i].addEventListener('mouseover', function(){ let currentTip = this.querySelector('div'); if(currentTip){ currentTip.style.visibility = 'visible'; currentTip.style.opacity = '1'; } }); eplLinkQuestionsMobile[i].addEventListener('mouseout', function(){ let currentTip = this.querySelector('div'); if(currentTip){ currentTip.style.visibility = 'hidden'; currentTip.style.opacity = '0'; } }); } } } offersEpcLinkTipMobile(); // Mechs from back || Pagination function fetchingOffersPage(pageNumber = 1, stockState = 0, fromPager){ const xhr = new XMLHttpRequest(); let page = '?page='+pageNumber; let stockStateStr = ''; if(fromPager != true){ if(stockState == 1){ stockStateStr = '&stock_state=1'; }else{ stockStateStr = '&stock_state=0'; } } else { stockStateStr = '='+stockState; } const finalItemCode = window.location.href.split('/')[6]; let requestUrl = `/catalog/offers/`+finalItemCode+`${page}${stockStateStr}`; let offersContainer = document.querySelector('.offersContainer'); let preloaderContainer = document.querySelector('.preloader-container'); xhr.open("POST", requestUrl, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); requestUrl = ''; //Smooth scroll to the proper position let viewportWidth = window.innerWidth; if(viewportWidth < 1140){ var yOffsetFetchingOffersPage = -5; } else { var yOffsetFetchingOffersPage = -100; } var elDistanceToTop = document.getElementsByClassName("stock-filter")[0].offsetTop + yOffsetFetchingOffersPage; window.scrollTo({top: elDistanceToTop, behavior: 'instant'}); offersContainer.style.display = 'none'; preloaderContainer.style.display = 'block'; xhr.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { const response = xhr.response; let responseHtml = document.createElement("div"); responseHtml.innerHTML = response; shopCatalogMechDesktop(); offersContainer.firstChild.replaceWith(responseHtml); offerCardMobileOpen(); offerCardMobileInfoOpen(); offerCardDesktopOpen(); offerCardDesktopInfoOpen(); offerCardMobileBuyButtonMech(); offerCardDesktopBuyButtonMech(); offerCardDesktopBuyButtonTooltip(); offerCardMobileFastBuy(); offerCardDesktopFastBuy(); offerCardDesktopBuyButtonTooltip(); offerCardDesktopFastBuyTooltipMech(); desktopCardMoreBtn(); offersEpcLinkTip(); offersEpcLinkTipMobile(); offersCardDesktopFavoriteBtnAdd(); offersCardDesktopFavoriteBtnRemove(); offerCardFavoriteBtnMobileAdd(); offerCardFavoriteBtnMobileRemove(); offersCatalogSortByPriceMechDesktop(); offersCatalogSortByPriceMechMobile(); shopCatalogPager(); catalogOffersAskModal(); generateNextOfferBtn(); preloaderContainer.style.display = 'none'; offersContainer.style.display = 'block'; } } xhr.send(requestUrl); } function shopCatalogPager(){ let pagerLinks = document.querySelectorAll('.pagination__list a'); for (let i = 0; i < pagerLinks.length; i++) { pagerLinks[i].addEventListener('click', function(e){ e.preventDefault(); let pageNumber = this.getAttribute('href').split('=')[1]; let stockState = this.getAttribute('href').split('=')[2]; fetchingOffersPage(pageNumber, stockState, true); }); } } function shopCatalogFilter(){ let stockCheckBox = document.getElementById('show_out_of_stock'); if (stockCheckBox != null) { if (stockCheckBox.checked == true) { stockCheckBox.checked = true; } else { stockCheckBox.checked = false; } stockCheckBox.addEventListener('change', () => { if (stockCheckBox.checked) { fetchingOffersPage(1, stockState = 1); } else { fetchingOffersPage(1, stockState = 0); } }); } } function generateNextOfferBtn(){ const finalItemCode = window.location.href.split('/')[6]; let nextOfferBtn = document.querySelector('.offers-catalog-next-btn'); console.warn('generateNextOfferBtn'); // console.warn('finalItemCode'); // console.warn(finalItemCode); let currentEl = document.querySelector('[data-code="'+finalItemCode+'"]') if(currentEl === null){ console.log('generateNextOfferBtn can`t find current element with current URL in link'); nextOfferBtn.style.display = 'none'; }else{ let nextElParent = currentEl.parentElement.nextElementSibling; // console.warn('nextElParent'); // console.warn(nextElParent); if(nextElParent == null) { // console.warn('nextElParent Null'); // console.warn(nextElParent); nextElParentWithLink = document.querySelector('a.final-item[data-code="'+finalItemCode+'"]'); if(nextElParentWithLink == null){ // console.warn('No final-item error! tag-link side effect - run mobileSideEffect function'); // generateNextOfferBtnMobileTagLink(); }else{ nextElParent = nextElParentWithLink.parentElement.nextElementSibling; } } if(nextElParent){ // console.warn('nextElParent +'); // console.warn(nextElParent); let nextElLink = nextElParent.querySelector('a').getAttribute('href'); let nextElText = nextElParent.querySelector('a').querySelectorAll('div')[1].innerText; if (nextOfferBtn) { nextOfferBtn.setAttribute('href', nextElLink); nextOfferBtn.querySelector('.offers-catalog-next-btn__text b').innerText = nextElText; } }else{ if (nextOfferBtn) { // console.warn('nextElParent Null 2'); // console.warn(nextElParent); nextOfferBtn.style.display = 'none'; } } } //exception on tag-link side effect error function generateNextOfferBtnMobileTagLink(){ const finalItemCode = window.location.href.split('/')[6]; const nextElParentWithLinkMobile = document.querySelector('a.final-item-mobile[data-code="'+finalItemCode+'"]'); console.warn('nextElParentWithLinkMobile +'); console.warn(nextElParentWithLinkMobile); if(nextElParentWithLinkMobile == null){ console.log('no mobile final item in generateNextOfferBtnMobileTagLink'); }else{ const nextElParentMobile = nextElParentWithLinkMobile.parentElement.nextElementSibling; console.warn('nextElParentMobile +'); console.warn(nextElParentMobile); } } } //JS helper for getCatalogTopLevelImageURL function in /dep/ function getCatalogTopLevelImageURLHelper(){ //check for /dep/ in URL if(/dep/.test(window.location.href)){ // console.warn('it`s /dep/-url page') //check breadcrumbs const breadList = document.querySelectorAll('.breadcrumbs li'); const thirdBreadLink = breadList[2]; if(thirdBreadLink){ const secondBreadLink = breadList[1].querySelector('a'); if(secondBreadLink.href.includes('/departments')){ // Perform actions for "/departments" const catalogDepPicture = document.querySelector('.catalog__departament-picture img'); if(catalogDepPicture){ if(catalogDepPicture.src == 'https://final.lr.ru/img/katalog1/PLUG-SHOP.png'){ catalogDepPicture.src = '/img/katalog1/PLUG-DEP-GRUPP.png'; catalogDepPicture.style.visibility = 'visible'; // console.log('Image src replaced to "/img/katalog1/PLUG-DEP-GRUPP.png"'); }else{ catalogDepPicture.style.visibility = 'visible'; // console.log('Image src is not "/img/katalog1/PLUG-SHOP.png", no action needed.'); } const firstShopCatalogTitlePicture = document.querySelector('.shop-catalog-desktop__title-picture img'); if(firstShopCatalogTitlePicture){ if(firstShopCatalogTitlePicture.src == 'https://final.lr.ru/img/katalog1/PLUG-SHOP.png'){ firstShopCatalogTitlePicture.src = '/img/katalog1/PLUG-DEP-GRUPP.png'; firstShopCatalogTitlePicture.style.visibility = 'visible'; }else{ firstShopCatalogTitlePicture.style.visibility = 'visible'; } } } }else if(secondBreadLink.href.includes('/models')){ // Perform actions for "/models" const catalogDepPicture = document.querySelector('.catalog__departament-picture img'); if(catalogDepPicture){ if(catalogDepPicture.src == 'https://final.lr.ru/img/katalog1/PLUG-SHOP.png'){ catalogDepPicture.src = '/img/katalog1/PLUG-DEP-MODEL.png'; catalogDepPicture.style.visibility = 'visible'; console.log('Image src replaced to "/img/katalog1/PLUG-DEP-MODEL.png"'); }else{ catalogDepPicture.style.visibility = 'visible'; console.log('Image src is not "/img/katalog1/PLUG-SHOP.png", no action needed.'); } const firstShopCatalogTitlePicture = document.querySelector('.shop-catalog-desktop__title-picture img'); if(firstShopCatalogTitlePicture){ if(firstShopCatalogTitlePicture.src == 'https://final.lr.ru/img/katalog1/PLUG-SHOP.png'){ firstShopCatalogTitlePicture.src = '/img/katalog1/PLUG-DEP-MODEL.png'; firstShopCatalogTitlePicture.style.visibility = 'visible'; }else{ firstShopCatalogTitlePicture.style.visibility = 'visible'; } } } }else{ // Handle other cases if needed console.warn('Do something for other cases'); } console.warn(secondBreadLink) } }else{ // console.warn('it`s NOT /dep/-url page') } } getCatalogTopLevelImageURLHelper() //JS Link-anchor helper for situatuation, when ling-anchor is finalItem in the same time function linkAnchorHelper(){ let secondItemMobileItem = document.querySelectorAll('.shop-catalog-mobile-item--second'); if(secondItemMobileItem === null){ console.log('no secondItemMobileItem'); }else{ secondItemMobileItem.forEach(item =>{ let secondItemMobileItemLink = item.querySelector('a'); let secondItemMobileItemLinkBackBtn = item.querySelector('.shop-catalog-mobile__tag-link--backward'); if(secondItemMobileItemLinkBackBtn){ console.warn('secondItemMobileItemLinkBackBtn HERE'); console.warn(secondItemMobileItemLinkBackBtn); secondItemMobileItemLink.classList.remove('final-item-mobile'); secondItemMobileItemLink.classList.add('link_anchor'); } }); } } //tag-link helper - text block remover function offersCatalogTagLinkTextRemover(){ const tagLinkBlock = document.querySelectorAll('.shop-catalog-desktop__tag-link-block') if(tagLinkBlock !== null){ tagLinkBlock.forEach(item => { const tagLinkBlockParent = item.parentElement; const tagLinkBlockParentText = tagLinkBlockParent.querySelector('.shop-catalog-desktop__item-text'); const tagLinkBlockParentPictureImg = tagLinkBlockParent.querySelector('.shop-catalog-desktop__item-picture img'); const tagLinkBlockParentPicture = tagLinkBlockParent.querySelector('.shop-catalog-desktop__item-picture'); const tagLinkBlockForward = item.querySelector('.shop-catalog-desktop__tag-link--forward'); if(tagLinkBlockParentText){ tagLinkBlockParentText.remove(); } if(tagLinkBlockForward){ tagLinkBlockForward.remove(); } if(tagLinkBlockParentPicture){ tagLinkBlockParentPictureImg.remove(); tagLinkBlockParentPicture.style.background = 'linear-gradient(180deg, #0C6773 23.44%, #E3E3E3 81.77%, rgba(255, 255, 255, 0) 100%)'; } const tagLinkBlockTagItem = tagLinkBlockParent.querySelector('.shop-catalog-desktop__tag-link-item'); const tagLinkBlockTagItemParentLink = tagLinkBlockTagItem.parentElement; const tagLinkBlockTagItemModel = tagLinkBlockParent.querySelector('.shop-catalog-desktop__tag-link-item .model'); const tagLinkBlockTagItemNoModelBlock = tagLinkBlockParent.querySelector('.modelNoOffer'); if(tagLinkBlockTagItemNoModelBlock === null){ tagLinkBlockTagItem.addEventListener('mouseover', function(){ tagLinkBlockTagItemModel.classList.add('model--hover'); }); tagLinkBlockTagItem.addEventListener('mouseout', function(){ tagLinkBlockTagItemModel.classList.remove('model--hover'); }); }else{ tagLinkBlockTagItemParentLink.style.pointerEvents = 'none'; } }); } } offersCatalogTagLinkTextRemover(); function offersCatalogMoreBtnHelper(){ const shortMobileOfferdCard = document.querySelectorAll('.short-mobile-card'); if(shortMobileOfferdCard !== null){ shortMobileOfferdCard.forEach(item => { const titleBlock = item.querySelector('.short-mobile-card__title'); if(titleBlock){ const titleBlockLink = titleBlock.href; const moreBtn = item.querySelector('.short-mobile-card__more'); if(moreBtn){ moreBtn.href = titleBlockLink; } }else{ const titleBlockUnavailable = item.querySelector('.short-mobile-card__title--no-offers'); if(titleBlockUnavailable){ const moreBtn = item.querySelector('.short-mobile-card__more'); if(moreBtn){ moreBtn.href = titleBlockUnavailable; } } } }); } } offersCatalogMoreBtnHelper(); //Code from deleted specialSlider.js - slider for special offers on mane page function specialSlider() { let modifiersForSpecial = { controlActive: 'special-slider__control--active', }; const elRoot = document.querySelector('.js-special-slider'); if (elRoot === null) { // console.log("specialSlider left html") } else { const elsItem = elRoot.querySelectorAll('.js-special-slider__item'); const elItems = elRoot.querySelector('.js-special-slider__items'); const elNext = elRoot.querySelector('.js-special-slider__next'); const elPrevious = elRoot.querySelector('.js-special-slider__previous'); //Max value is scrollWidth - clientWidth, since it's the right side of the block const maxScrollValue = elItems.scrollWidth - elRoot.clientWidth; //State values let currentSlide = 0; let currentX = 0; //Toggle controls visibility const updateControls = () => { //Hide previous button if we are at the start elPrevious.classList.toggle(modifiersForSpecial.controlActive, currentX !== 0); //Hide next button if we are at the end elNext.classList.toggle(modifiersForSpecial.controlActive, currentX < maxScrollValue); }; //Slide to card by its index const slideTo = (index) => { //Check for minimal/maximal valid endexes if(index < 0 || index > elItems.length - 1) return; //Get total width of all items. CSS is built the way that items don't have any offsets between them. //Padding are used for that reason let scrollValue = 0; for(let i = 0; i < index; i++) { scrollValue += elsItem[i].clientWidth; } //Limit by maximal scroll value const targetValue = Math.min(scrollValue, maxScrollValue); //Scroll to card elItems.scrollTo({left: targetValue, behavior: 'smooth'}); //Update state values and controls currentSlide = index; currentX = targetValue; updateControls(); }; //Update controls on page load, They start hidden not to have visible controls that can't be clicked while js still loads. updateControls(); //Whenever you click controls you go to next or previous index elNext.addEventListener('click', () => slideTo(currentSlide + 1)); elPrevious.addEventListener('click', () => slideTo(currentSlide - 1)); } } specialSlider(); // special card tips on adaptive cards function favBtnTooltipAdaptive(){ let favBtnsDefaultList = document.querySelectorAll('.special-offer-catalog__card-favorite--default'); let favBtnsActiveList = document.querySelectorAll('.special-offer-catalog__card-favorite--active'); if(favBtnsDefaultList === null){ // console.log('no adaptive cards on the page'); }else { let intViewportWidth = window.innerWidth; if(intViewportWidth > 1140){ for(let i = 0; i < favBtnsDefaultList.length; i++){ favBtnsDefaultList[i].addEventListener('mouseover', function(){ let currentTooltip = this.querySelector('.special-offer-catalog__card-favorite-default-tip'); currentTooltip.style.visibility = 'visible'; currentTooltip.style.opacity = '1'; }); favBtnsDefaultList[i].addEventListener('mouseout', function(){ let currentTooltip = this.querySelector('.special-offer-catalog__card-favorite-default-tip'); currentTooltip.style.visibility = 'hidden'; currentTooltip.style.opacity = '0'; }); } for(let i = 0; i < favBtnsActiveList.length; i++){ favBtnsActiveList[i].addEventListener('mouseover', function(){ let currentTooltip = this.querySelector('.special-offer-catalog__card-favorite-active-tip'); currentTooltip.style.visibility = 'visible'; currentTooltip.style.opacity = '1'; }); favBtnsActiveList[i].addEventListener('mouseout', function(){ let currentTooltip = this.querySelector('.special-offer-catalog__card-favorite-active-tip'); currentTooltip.style.visibility = 'hidden'; currentTooltip.style.opacity = '0'; }); } } } } favBtnTooltipAdaptive(); function singleOfferSlider(){ let slides = document.querySelectorAll('.activeSlide__slider-item'); let prevBtn = document.querySelector('.activeSlide__prev-slide'); let nextBtn = document.querySelector('.activeSlide__next-slide'); if(prevBtn){ let thumbnailsContainer = document.querySelector('.vendor-slider__thumbnails-inner'); let activeThumbnail = document.querySelector('.activeSlide__active-thumbnail'); let slidesMassiveArray = slides.length; console.warn('slidesMassiveArray'); console.warn(slidesMassiveArray); if(slidesMassiveArray == 1){ console.warn('slidesMassiveArray = 1'); // console.warn(slidesMassiveArray); }else{ let slideIndex = 1; showSlides(slideIndex); function nextSlide() { showSlides(slideIndex += 1); } function previousSlide() { showSlides(slideIndex -= 1); } function currentSlide(n) { showSlides(slideIndex = n); } function showSlides(n){ let i; if (n > slides.length) { slideIndex = 1; } if (n < 1) { slideIndex = slides.length; } for (let slide of slides) { slide.style.display = "none"; } let incapSlides = slides[slideIndex - 1] if(incapSlides){ incapSlides.style.display = "flex"; } } if(prevBtn){ prevBtn.addEventListener('click', function(){ activeThumbnail.style.display = 'none'; showSlides(slideIndex -= 1); }); nextBtn.addEventListener('click', function(){ // removeVideoFromActiveThumb(); activeThumbnail.style.display = 'none'; showSlides(slideIndex += 1); }); } //thumbnail initial slides.forEach(item => { let currentItem = item; const currentItemImg = currentItem.querySelector('img'); let currentItemImgRealWidth = currentItemImg.naturalWidth; let intViewportWidth = window.innerWidth; if(intViewportWidth < 768){ currentItemImg.style.objectFit = 'contain'; currentItemImg.style.width = '100%'; currentItemImg.style.height = '100%'; }else{ if(currentItemImgRealWidth < 550){ currentItemImg.style.objectFit = 'contain'; currentItemImg.style.width = 'auto'; currentItemImg.style.height = 'inherit'; }else{ currentItemImg.style.objectFit = 'contain'; currentItemImg.style.width = '100%'; currentItemImg.style.height = '100%'; } } console.warn('currentItemImg') console.warn(currentItemImg) console.warn('currentItemImgRealWidth') console.warn(currentItemImgRealWidth) let slideThubmnail = document.createElement("div"); thumbnailsContainer.appendChild(slideThubmnail); slideThubmnail.classList.add('vendor-slider__thumbnail'); slideThubmnail.innerHTML = currentItem.innerHTML; let slideThumbnailImg = slideThubmnail.querySelector('img'); if(slideThumbnailImg){ slideThumbnailImg.style.objectFit = 'contain'; slideThumbnailImg.style.width = '100%'; slideThumbnailImg.style.height = '100%'; } }); hideArrows(); } } } singleOfferSlider(); function hideArrows() { let prevArrow = document.querySelector('.activeSlide__prev-slide'); let nextArrow = document.querySelector('.activeSlide__next-slide'); let activeSlide = document.querySelector('.activeSlide'); if (prevArrow) { let intViewportWidth = window.innerWidth; if(intViewportWidth < 1100){ console.warn('mobile'); console.log(intViewportWidth); prevArrow.style.display = 'flex'; nextArrow.style.display = 'flex'; }else{ console.warn('desktop'); console.log(intViewportWidth); // Check for cursor position document.addEventListener('mousemove', checkCursorPosition); activeSlide.addEventListener('mouseover', function(){ prevArrow.style.display = 'flex'; nextArrow.style.display = 'flex'; }); activeSlide.addEventListener('mouseout', function(){ prevArrow.style.display = 'none'; nextArrow.style.display = 'none'; }); function checkCursorPosition(e) { let x = e.clientX, y = e.clientY; if (x >= activeSlide.offsetLeft && x <= (activeSlide.offsetLeft + activeSlide.offsetWidth) && y >= activeSlide.offsetTop && y <= (activeSlide.offsetTop + activeSlide.offsetHeight)) { prevArrow.style.display = 'flex'; nextArrow.style.display = 'flex'; document.removeEventListener('mousemove', checkCursorPosition); } } } } } function thumbnailSliderPart(){ let activeThumbnail = document.querySelector('.activeSlide__active-thumbnail'); let thumbnails = document.querySelectorAll('.vendor-slider__thumbnail'); let thumbnailsInner = document.querySelector('.vendor-slider__thumbnails-inner'); let prevBtn = document.querySelector('.activeSlide__prev-slide'); let nextBtn = document.querySelector('.activeSlide__next-slide'); if(activeThumbnail) { for (let i = 0;i < thumbnails.length; i++){ thumbnails[i].addEventListener('click', function(){ let activeThumb = this; let activeThumbImg = activeThumb.querySelector('img'); let activeThumbImgHeight = activeThumbImg.naturalHeight; let activeThumbImgWidth = activeThumbImg.naturalWidth; // console.warn('activeThumbImgWidth'); // console.warn(activeThumbImgWidth); if(activeThumbImgWidth < 450){ activeThumbnail.style.display ='flex'; activeThumbnail.innerHTML = activeThumb.innerHTML; let activeThumbnailImg = activeThumbnail.querySelector('img'); activeThumbnailImg.style.objectFit = 'contain'; activeThumbnailImg.style.width = 'auto'; activeThumbnailImg.style.height = 'inherit'; }else{ activeThumbnail.style.display ='flex'; activeThumbnail.innerHTML = activeThumb.innerHTML; let activeThumbnailImg = activeThumbnail.querySelector('img'); } }); } let intViewportWidth = window.innerWidth; if(intViewportWidth > 1140){ if(thumbnails.length > 4){ let thumbnailsCountNumber = thumbnails.length - 4; let thumbnailCounter = document.createElement('div'); thumbnailCounter.classList.add('vendor-slider__thumbnail-counter') thumbnailCounter.innerHTML = ` <span>${thumbnailsCountNumber}</span> `; // console.warn(' thumbnails.length'); // console.warn( thumbnails.length); thumbnails[3].after(thumbnailCounter); thumbnails[3].style.pointerEvents = 'none'; let thumbnailCounterSpan = thumbnailCounter.querySelector('span'); //show all thumbnails thumbnailCounterSpan.addEventListener('click', function(){ thumbnailsInner.classList.remove('vendor-slider__thumbnails-inner'); thumbnailsInner.classList.add('vendor-slider__thumbnails-inner--active'); thumbnailCounter.style.display = 'none'; thumbnails[3].style.pointerEvents = 'auto'; }); prevBtn.addEventListener('click', function(){ thumbnailsInner.classList.add('vendor-slider__thumbnails-inner'); thumbnailsInner.classList.remove('vendor-slider__thumbnails-inner--active'); thumbnailCounter.style.display = 'flex'; }); nextBtn.addEventListener('click', function(){ thumbnailsInner.classList.add('vendor-slider__thumbnails-inner'); thumbnailsInner.classList.remove('vendor-slider__thumbnails-inner--active'); thumbnailCounter.style.display = 'flex'; }); } } } } thumbnailSliderPart(); // Video in slider function generateVideoInSlider(){ let videosBlock = document.querySelectorAll('.activeSlide__slider-video'); if (videosBlock === null) { // console.log("sliderVideos left HTML"); } else { for (let i = 0; i < videosBlock.length; i++) { setupVideo(videosBlock[i]); } function setupVideo(video) { let link = video.querySelector('.activeSlide__video-link'); let media = video.querySelector('.activeSlide__media'); let button = video.querySelector('.activeSlide__button'); let id = parseMediaURL(media); video.addEventListener('click', () => { let iframe = createIframe(id); link.remove(); button.remove(); video.appendChild(iframe); link.removeAttribute('href'); video.classList.add('video--enabled'); videoControlSingleOfferPage(); }); } function parseMediaURL(media) { let regexp = /https:\/\/i\.ytimg\.com\/vi\/([a-zA-Z0-9_-]+)\/maxresdefault\.jpg/i; let url = media.src; let match = url.match(regexp); return match[1]; } function createIframe(id) { let iframe = document.createElement('iframe'); iframe.setAttribute('allowfullscreen', ''); iframe.setAttribute('allow', 'autoplay'); iframe.setAttribute('src', generateURL(id)); iframe.classList.add('video__media'); return iframe; } function generateURL(id) { let query = '?rel=0&showinfo=0&autoplay=1&enablejsapi=1'; return 'https://www.youtube.com/embed/' + id + query; } } } // generateVideoInSlider(); function videoControlSingleOfferPage(){ let iframes = document.querySelectorAll('iframe'); let nextBtn = document.querySelectorAll('.activeSlide__next-slide'); let prevBtn = document.querySelectorAll('.activeSlide__prev-slide'); let thumbnailPanel = document.querySelector('.vendor-slider__thumbnails') for(let i = 0; i < nextBtn.length; i++){ nextBtn[i].addEventListener('click', function(){ // console.warn('BAM!!'); var stopAllYouTubeVideos = () => { var iframes = document.querySelectorAll('iframe'); Array.prototype.forEach.call(iframes, iframe => { iframe.contentWindow.postMessage(JSON.stringify({ event: 'command', func: 'pauseVideo' }), '*'); }); } stopAllYouTubeVideos(); }); } for(let i = 0; i < prevBtn.length; i++){ prevBtn[i].addEventListener('click', function(){ // console.warn('BAM!!'); var stopAllYouTubeVideos = () => { var iframes = document.querySelectorAll('iframe'); Array.prototype.forEach.call(iframes, iframe => { iframe.contentWindow.postMessage(JSON.stringify({ event: 'command', func: 'pauseVideo' }), '*'); }); } stopAllYouTubeVideos(); }); } window.addEventListener('scroll', function(){ let pauseAllYouTubeVideos = () => { let iframes = document.querySelectorAll('iframe'); Array.prototype.forEach.call(iframes, iframe => { iframe.contentWindow.postMessage(JSON.stringify({ event: 'command', func: 'pauseVideo' }), '*'); }); } pauseAllYouTubeVideos(); }); thumbnailPanel.addEventListener('click', function(){ let pauseAllYouTubeVideos = () => { let iframes = document.querySelectorAll('iframe'); Array.prototype.forEach.call(iframes, iframe => { iframe.contentWindow.postMessage(JSON.stringify({ event: 'command', func: 'pauseVideo' }), '*'); }); } pauseAllYouTubeVideos(); }); } function tumbnailVideo(){ let videosInSlider = document.querySelectorAll('.activeSlide__slider-video'); let videosliderThubmnails = document.querySelectorAll('.vendor-slider__thumbnail'); let activeThumbnail = document.querySelector('.activeSlide__active-thumbnail'); if (videosInSlider === null || videosliderThubmnails === null || activeThumbnail === null) { // console.log("videoInSlider left HTML"); } else { videosliderThubmnails.forEach(item => { let videoInThumb = item.querySelector('.activeSlide__slider-video'); if (videoInThumb === null){ // console.log("No video in slider!"); } else{ let previewOfVideo = videoInThumb.querySelector('.activeSlide__video-link'); item.classList.remove('vendor-slider__thumbnail'); item.classList.add('vendor-slider__thumbnail--video'); let videoThumb = item; // console.log(videoThumb); item.innerHTML = previewOfVideo.innerHTML; } }); } } // tumbnailVideo(); //remove video from thumb function removeVideoFromActiveThumb(){ let activeThumbnail = document.querySelector('.activeSlide__active-thumbnail'); let iframeActiveThumb = activeThumbnail.querySelector('iframe'); if (activeThumbnail === null || iframeActiveThumb === null){ // console.log('NO VIDEO IN ACTIVEThumb'); } else { iframeActiveThumb.remove(); } } //Generate video from THUMB function generateVideoInSliderFromThumb(){ let activeThumb = document.querySelector('.activeSlide__active-thumbnail'); let videoInSlide = document.querySelectorAll('.activeSlide__slider-video'); let videoThumb = document.querySelectorAll('.vendor-slider__thumbnail--video'); if(activeThumb === null || videoInSlide === null || videoThumb === null){ // console.log('no Video in slider'); }else{ function setupVideo() { for(let i = 0; i < videoThumb.length; i++){ videoThumb[i].addEventListener('click', function(){ let currentThumb = this; let media = currentThumb.querySelector('.activeSlide__media'); let button = currentThumb.querySelector('.activeSlide__button'); let id = parseMediaURL(media); let iframe = createIframe(id); // button.remove(); activeThumb.style.display = 'flex'; activeThumb.appendChild(iframe); }); } } setupVideo(); function parseMediaURL(media) { let regexp = /https:\/\/i\.ytimg\.com\/vi\/([a-zA-Z0-9_-]+)\/maxresdefault\.jpg/i; let url = media.src; let match = url.match(regexp); return match[1]; } function createIframe(id) { let iframe = document.createElement('iframe'); iframe.setAttribute('allowfullscreen', ''); iframe.setAttribute('allow', 'autoplay'); iframe.setAttribute('src', generateURL(id)); iframe.classList.add('video__media'); return iframe; } function generateURL(id) { let query = '?rel=0&showinfo=0&autoplay=1&enablejsapi=1'; return 'https://www.youtube.com/embed/' + id + query; } videoControlSingleOfferPage(); } } // generateVideoInSliderFromThumb(); function singleOfferPageAskButtonTip(){ const askBtns = document.querySelectorAll('.single-vendor-description__panel--ask'); if(askBtns){ for(let i = 0; i < askBtns.length; i++){ askBtns[i].addEventListener('mouseover', function(){ let currentTipAsk = this.querySelector('.single-vendor-description__panel--ask-tip'); currentTipAsk.style.visibility = 'visible'; currentTipAsk.style.opacity = '1'; }); askBtns[i].addEventListener('mouseout', function(){ let currentTipAsk = this.querySelector('.single-vendor-description__panel--ask-tip'); currentTipAsk.style.visibility = 'hidden'; currentTipAsk.style.opacity = '0'; }); } } } singleOfferPageAskButtonTip(); function singleOfferPageShareButtonTip(){ const shareBtns = document.querySelectorAll('.single-vendor-description__panel--share'); if(shareBtns){ for(let i = 0; i < shareBtns.length; i++){ shareBtns[i].addEventListener('mouseover', function(){ let currentTipShare = this.querySelector('.single-vendor-description__panel--share-tip'); currentTipShare.style.visibility = 'visible'; currentTipShare.style.opacity = '1'; }); shareBtns[i].addEventListener('mouseout', function(){ let currentTipShare = this.querySelector('.single-vendor-description__panel--share-tip'); currentTipShare.style.visibility = 'hidden'; currentTipShare.style.opacity = '0'; }); } } } singleOfferPageShareButtonTip(); //favorite tips/mech function singleOfferPageFavoriteButtonTip(){ const favoriteBtns = document.querySelectorAll('.single-vendor-description__panel--favorite'); const favoriteBtnsActive = document.querySelectorAll('.single-vendor-description__panel--favorite-active'); if(favoriteBtns){ for(let i = 0; i < favoriteBtns.length; i++){ favoriteBtns[i].addEventListener('mouseover', function(){ let currentTipFav = this.querySelector('.single-vendor-description__panel--favorite-tip'); currentTipFav.style.visibility = 'visible'; currentTipFav.style.opacity = '1'; }); favoriteBtns[i].addEventListener('mouseout', function(){ let currentTipFav = this.querySelector('.single-vendor-description__panel--favorite-tip'); currentTipFav.style.visibility = 'hidden'; currentTipFav.style.opacity = '0'; }); } for(let i = 0; i < favoriteBtnsActive.length; i++){ favoriteBtnsActive[i].addEventListener('mouseover', function(){ let currentTipFav = this.querySelector('.single-vendor-description__panel--favorite-tip'); currentTipFav.style.visibility = 'visible'; currentTipFav.style.opacity = '1'; }); favoriteBtnsActive[i].addEventListener('mouseout', function(){ let currentTipFav = this.querySelector('.single-vendor-description__panel--favorite-tip'); currentTipFav.style.visibility = 'hidden'; currentTipFav.style.opacity = '0'; }); } } } singleOfferPageFavoriteButtonTip(); function singleOfferPageFavoriteMech(){ const favWrapper = document.querySelector('.single-vendor-description__panel--favorite-wrapper'); if(favWrapper){ const favBtn = favWrapper.querySelector('.single-vendor-description__panel--favorite'); const favBtnActive = favWrapper.querySelector('.single-vendor-description__panel--favorite-active'); const headerDesktopFavSpan = document.querySelector('.user__favorites span'); const headerMobileFavSpan = document.querySelector('.user-mobile__favorites span'); let favBtnKey = favBtn.dataset.key; favBtn.addEventListener('click', function(){ let xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/add'); xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhr.onload = () => { if (xhr.status === 200) { const jsonResponse = JSON.parse(xhr.responseText); let countFavFromServer = ++jsonResponse.count; headerDesktopFavSpan.innerText = countFavFromServer; headerMobileFavSpan.innerText = countFavFromServer; favBtn.style.display = 'none'; favBtnActive.style.display = 'block'; // mobileFavoriteTooltip(); stickyHeaderDesktopFavoriteCountUpdate(); trackFavoriteCount(); stickyHeaderMobileFavCountUpdate(); trackFavoriteCountMobile(); }else { console.warn('singleFavoriteMobileMech ajax error'); } } xhr.send('key=' + favBtnKey); }); favBtnActive.addEventListener('click', function(){ let xhr = new XMLHttpRequest(); xhr.open('POST', '/favorite/remove'); xhr.setRequestHeader('Content-Type', "application/x-www-form-urlencoded"); xhr.onload = () => { if (xhr.status === 200) { const jsonResponse = JSON.parse(xhr.responseText);; let countFavFromServer = --jsonResponse.count; headerDesktopFavSpan.innerText = countFavFromServer; headerMobileFavSpan.innerText = countFavFromServer; favBtnActive.style.display = 'none'; favBtn.style.display = 'block'; // mobileFavoriteTooltip(); stickyHeaderDesktopFavoriteCountUpdate(); trackFavoriteCount(); stickyHeaderMobileFavCountUpdate(); trackFavoriteCountMobile(); }else { console.warn('singleFavoriteMobileMech ajax error'); } } xhr.send('key=' + favBtnKey); }); } } singleOfferPageFavoriteMech(); //ask/share btns open on single page function singleOfferPageModalOpener() { const askBtn = document.querySelector('.single-vendor-description__panel--ask'); const shareBtn = document.querySelector('.single-vendor-description__panel--share'); const body = document.querySelector('body'); if (askBtn) { // Ask modal logic const modalAsk = document.querySelector('.modal-ask'); const askModalBlur = document.querySelector('.modal-ask__blur'); const btnAskModalClose = document.querySelectorAll('.modal-ask__close'); const modalAskBtnDone = document.querySelector('.modal-ask__btn--done'); const askModalForm = document.querySelector('.modal-ask__form-inner'); function openAskModal(e) { e.preventDefault(); modalAsk.classList.add('modal-ask--on'); body.classList.add('page-body__no-scroll'); askModalForm.classList.add('modal-ask__form-inner--opening'); } function closeAskModal() { askModalForm.classList.remove('modal-ask__form-inner--opening'); askModalForm.classList.add('modal-ask__form-inner--closing'); const handleAnimationEnd = function() { modalAsk.classList.remove('modal-ask--on'); askModalForm.classList.remove('modal-ask__form-inner--closing'); body.classList.remove('page-body__no-scroll'); askModalForm.removeEventListener('animationend', handleAnimationEnd); }; askModalForm.addEventListener('animationend', handleAnimationEnd); } askBtn.addEventListener('click', openAskModal); btnAskModalClose.forEach(item => item.addEventListener('click', closeAskModal)); modalAskBtnDone.addEventListener('click', closeAskModal); askModalBlur.addEventListener('click', closeAskModal); // Share modal logic const shareModal = document.querySelector('.modal-share'); const shareModalBlur = document.querySelector('.modal-share__blur'); const btnShareModalClose = document.querySelector('.modal-share__close'); const shareModalWrapper = document.querySelector('.modal-share__wrapper'); function openShareModal(e) { e.preventDefault(); shareModal.classList.add('modal-share--on'); body.classList.add('page-body__no-scroll'); shareModalWrapper.classList.add('modal-share__wrapper--opening'); } function closeShareModal() { shareModalWrapper.classList.remove('modal-share__wrapper--opening'); shareModalWrapper.classList.add('modal-share__wrapper--closing'); const handleAnimationEnd = function() { shareModal.classList.remove('modal-share--on'); shareModalWrapper.classList.remove('modal-share__wrapper--closing'); body.classList.remove('page-body__no-scroll'); shareModalWrapper.removeEventListener('animationend', handleAnimationEnd); }; shareModalWrapper.addEventListener('animationend', handleAnimationEnd); } shareBtn.addEventListener('click', openShareModal); btnShareModalClose.addEventListener('click', closeShareModal); shareModalBlur.addEventListener('click', closeShareModal); } } singleOfferPageModalOpener(); //ask form mech function singleOfferPageAskMech(){ const modalAskForm = document.querySelector('.modal-ask__form-wrapper'); const modalAskFormInner = document.querySelector('.modal-ask__form-inner'); const modalAskFormActiveState = document.querySelector('.modal-ask__form-inner--done'); const modalAskFromBtn = document.querySelector('.modal-ask__btn'); const modalAskFromInputs = document.querySelectorAll('.modal-ask__input'); const modalAskFromTextArea = document.querySelector('.modal-ask__field'); if(modalAskForm){ modalAskFromBtn.addEventListener('click', function(){ function inputsValidation(callback){ let nameInput = modalAskFromInputs[0]; let nameInputValue = nameInput.value; let emailInput = modalAskFromInputs[1]; let emailInputValue = emailInput.value; //проверка поля ФИО //паттерн для имени - только английские и русские буквы + символ "-" let namePattern = /^[a-zA-Zа-яА-ЯёЁ\s\-]+$/; if(namePattern.test(nameInputValue)){ console.log('input valid'); if (callback) { callback(); } }else{ nameInput.style.border = '2px solid #F73D34'; nameInput.style.outline = 'none'; nameInput.value = ''; nameInput.placeholder = 'Недопустимые символы!'; function delayNameInputRefresh(){ nameInput.style.border = '1px solid #174F82'; nameInput.style.outline = '1px solid #0A51A5'; nameInput.placeholder = 'Ваше имя'; } nameInput.addEventListener('click', function(){ delayNameInputRefresh(); }); setTimeout(delayNameInputRefresh, 7070); } //проверка поля email let mailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; if(mailPattern.test(emailInputValue)){ console.log('input valid'); }else{ emailInput.style.border = '2px solid #F73D34'; nameInput.style.outline = 'none'; emailInput.value = ''; emailInput.placeholder = 'Неверно введен email!'; function delayMailInputRefresh(){ emailInput.style.border = '1px solid #174F82'; nameInput.style.outline = '1px solid #0A51A5'; emailInput.placeholder = 'Ваш email'; } emailInput.addEventListener('click', function(){ delayMailInputRefresh(); }); setTimeout(delayMailInputRefresh, 7070); } } function sendAskForm(){ console.warn('sendAskForm execute!') const xhr = new XMLHttpRequest(); const formData = new FormData(modalAskForm); xhr.open('POST', '/form/question-send'); xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status == 200) { // modalAskFormInner.style.visibility = 'hidden'; modalAskFormActiveState.style.display = 'flex'; }else { console.warn('askFromMech on singleVendorPage ajax error'); } } xhr.send(formData); } inputsValidation(sendAskForm); }); } } singleOfferPageAskMech() function singleOfferVendorPageBuyButtonMechDesktop(){ //check if single slider here let singleSlider = document.querySelector('.single-offer-vendor-page__inner'); if(singleSlider){ const offersFullCardList = document.querySelectorAll('.desktop-card-item'); let body = document.querySelector('body'); let cartBtnDesktopMainHeaderSpan = document.querySelector('.user__shopping-cart span'); for(let i = 0; i < offersFullCardList.length; i++){ let offerManufacturer = offersFullCardList[i].querySelector('.desktop-properties__manufacturer'); let offerPrice = offersFullCardList[i].querySelector('.desktop-card-item__price'); let offerbuyBtns = offersFullCardList[i].querySelectorAll('.desktop-buy__buy-btn'); for (let i = 0; i < offerbuyBtns.length; i++){ offerbuyBtns[i].addEventListener('click', function buyBtnFunc(e) { e.preventDefault(); localStorage.setItem('noModalCustomQuantityInputValue', ''); let thisBtn = this; thisBtn.classList.remove('desktop-buy__buy-btn'); thisBtn.classList.add('desktop-buy__buy-btn--load'); thisBtn.innerHTML = `<div class="desktop-buy__buy-btn-preloader"></div>`; let key = encodeURIComponent(thisBtn.dataset.key); let availability = thisBtn.dataset.availability; function sendOfferToCart() { const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardDesktopBuyButtonMech ajax error'); errorBannerDesktopRemove(); errorBannerDesktop(); thisBtn.classList.remove('desktop-buy__buy-btn--load'); thisBtn.classList.add('desktop-buy__buy-btn'); thisBtn.innerHTML = ` `; }else{ const response = xhr.response; let currentPreloader = thisBtn.querySelector('.desktop-buy__buy-btn-preloader'); currentPreloader.remove(); thisBtn.classList.remove('desktop-buy__buy-btn--load'); thisBtn.classList.add('desktop-buy__buy-btn'); thisBtn.innerHTML = ` `; let parentBuyBlockDesktop = thisBtn.parentElement; let currentFastBtn = parentBuyBlockDesktop.querySelector('.desktop-buy__fast-buy-btn'); let desktopCardItemInner = parentBuyBlockDesktop.parentElement; //Availability sign of offer let offerCardAvailableSign = desktopCardItemInner.querySelector('.desktop-description__shop'); if(currentFastBtn){ //Hide buttons thisBtn.style.display = 'none'; currentFastBtn.style.display = 'none'; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Add quantity btns instead buy btn let quantityParent = document.createElement('div'); quantityParent.classList.add('desktop-buy-quantity'); let quantityCustomParent = document.createElement('div'); quantityCustomParent.classList.add('desktop-buy-quantity--custom'); quantityParent.innerHTML = ` <div class="desktop-buy-quantity__btn-minus" data-key="${key}"></div> <input class="desktop-buy-quantity__default-input" placeholder="1"> <div class="desktop-buy-quantity__btn-plus" data-key="${key}"></div> `; quantityCustomParent.innerHTML = ` <div class="desktop-buy-quantity__back-btn"></div> <div class="desktop-buy-quantity__custom-input-wrapper"> <input class="desktop-buy-quantity__custom-input" pattern="[0-9]*" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a class="desktop-buy-quantity__buy-btn"></a> </div> `; parentBuyBlockDesktop.appendChild(quantityParent); parentBuyBlockDesktop.appendChild(quantityCustomParent); const afterBuyMinusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-minus'); const afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyCustomInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyPlusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-plus'); const afterBuyQuantityBuyButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__buy-btn'); //function for checking availability and hide plus-btn if it`s required function checkAvailabilityBeforeClick(){ let afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyInputPlaceholder = afterBuyInput.placeholder; if(Number(afterBuyInputPlaceholder) >= Number(availability)){ // console.warn('afterBuyInputPlaceholder >= availability'); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus--disable'); afterBuyInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClick(); afterBuyMinusButton.addEventListener('click', function(){ //Mechanic after click on Minus button if(afterBuyInput.placeholder == '1'){ const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Quantity + - hidden quantityParent.remove(); quantityCustomParent.remove(); //Fast buy & buy btn onn currentFastBtn.style.display = 'block'; thisBtn.style.display = 'block'; } } xhr.send(params); }else{ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ // If 1 offer in afterBuyInputBlock checking const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); --afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus--disable'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus'); afterBuyInput.style.pointerEvents = 'auto'; } } xhr.send(params); } }); afterBuyPlusButton.addEventListener('click', function(){ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); ++afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; checkAvailabilityBeforeClick(); } } xhr.send(params); }); afterBuyInput.addEventListener('click', function(){ quantityParent.style.display = 'none'; quantityCustomParent.style.display = 'flex'; const afterBuyCustomQuantityInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyCustomQuantityBackBtn = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__back-btn'); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyInput.placeholder); afterBuyCustomQuantityInput.value = afterBuyInput.placeholder; afterBuyCustomQuantityInput.focus(); afterBuyCustomQuantityInput.addEventListener('input', function updateCustomInputValue(e){ const afterBuyCustomQuantityInputValue = afterBuyCustomQuantityInput.value; if(Number(afterBuyCustomQuantityInput.value) < Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); }else if(Number(afterBuyCustomQuantityInput.value) >= Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyCustomQuantityInput.value = availability; localStorage.setItem('noModalCustomQuantityInputValue', availability); }else if(availability === 'много' || availability === 'В наличии' || availability === 'По запросу'){ localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); } }); afterBuyCustomQuantityBackBtn.addEventListener('click', function(){ quantityCustomParent.style.display = 'none'; quantityParent.style.display = 'flex'; }); }); afterBuyQuantityBuyButton.addEventListener('click', function(e){ e.preventDefault(); let noModalCustomQuantityInputValue = localStorage.getItem('noModalCustomQuantityInputValue'); if(noModalCustomQuantityInputValue == ''){ // console.warn('noModalCustomQuantityInputValue === empty string'); }else{ // console.warn('noModalCustomQuantityInputValue'); // console.warn(noModalCustomQuantityInputValue); let thisBtn = this; thisBtn.classList.remove('desktop-buy-quantity__buy-btn'); thisBtn.classList.add('desktop-buy-quantity__buy-btn--load'); thisBtn.innerHTML = `<div class="desktop-custom-quantity-buy__buy-btn-preloader"></div>`; function sendOfferToCartDesktopCustomQuamnity(){ const params = new URLSearchParams(); params.set('id', key); params.append('qty', noModalCustomQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('modalCustomQuantityBuyButtonMech ajax error'); } else { // console.warn('modalCustomQuantityBuyButtonMech ajax SUCCESS'); thisBtn.classList.remove('desktop-buy-quantity__buy-btn--load'); thisBtn.classList.add('desktop-buy-quantity__buy-btn'); thisBtn.innerHTML = ` `; // dynamic data from cart const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); afterBuyInput.placeholder = noModalCustomQuantityInputValue; quantityParent.style.display = 'flex'; quantityCustomParent.style.display = 'none'; checkAvailabilityBeforeClick(); } } xhr.send(params); } setTimeout(sendOfferToCartDesktopCustomQuamnity, 300); } }); //init parent + add tooltip offerCardDesktopBuyModalLocalStorageSwitcherHide(); }else{ let currentFastBtnSuccess = parentBuyBlockDesktop.querySelector('.desktop-buy__fast-buy-btn--success'); if(currentFastBtnSuccess){ //Hide buttons thisBtn.style.display = 'none'; currentFastBtnSuccess.style.display = 'none'; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; // console.warn(cartBtnDesktopMainHeaderSpan); stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Add quantity btns instead buy btn let quantityParent = document.createElement('div'); quantityParent.classList.add('desktop-buy-quantity'); let quantityCustomParent = document.createElement('div'); quantityCustomParent.classList.add('desktop-buy-quantity--custom'); quantityParent.innerHTML = ` <div class="desktop-buy-quantity__btn-minus" data-key="${key}"></div> <input class="desktop-buy-quantity__default-input" placeholder="1"> <div class="desktop-buy-quantity__btn-plus" data-key="${key}"></div> `; quantityCustomParent.innerHTML = ` <div class="desktop-buy-quantity__back-btn"></div> <div class="desktop-buy-quantity__custom-input-wrapper"> <input class="desktop-buy-quantity__custom-input" pattern="[0-9]*" placeholder="1" type = "number" maxlength = "3" oninput="javascript: if (this.value.length > this.maxLength) this.value = this.value.slice(0, this.maxLength); this.value = !!this.value && Math.abs(this.value) >= 1 ? Math.abs(this.value) : null"> <a class="desktop-buy-quantity__buy-btn"></a> </div> `; parentBuyBlockDesktop.appendChild(quantityParent); parentBuyBlockDesktop.appendChild(quantityCustomParent); const afterBuyMinusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-minus'); const afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyCustomInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyPlusButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__btn-plus'); const afterBuyQuantityBuyButton = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__buy-btn'); function checkAvailabilityBeforeClick(){ let afterBuyInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__default-input'); let afterBuyInputPlaceholder = afterBuyInput.placeholder; if(Number(afterBuyInputPlaceholder) >= Number(availability)){ // console.warn('afterBuyInputPlaceholder >= availability'); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus--disable'); afterBuyInput.style.pointerEvents = 'none'; } } checkAvailabilityBeforeClick(); afterBuyMinusButton.addEventListener('click', function(){ //Mechanic after click on Minus button if(afterBuyInput.placeholder == '1'){ const params = new URLSearchParams(); params.set('id', key); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/remove'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('offerCardDesktopquantityDeleteButtonMech ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); //Quantity + - hidden quantityParent.remove(); quantityCustomParent.remove(); //Fast buy & buy btn onn currentFastBtnSuccess.style.display = 'block'; thisBtn.style.display = 'block'; } } xhr.send(params); }else{ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/reduce'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ // If 1 offer in afterBuyInputBlock checking const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); --afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; afterBuyPlusButton.classList.remove('desktop-buy-quantity__btn-plus--disable'); afterBuyPlusButton.classList.add('desktop-buy-quantity__btn-plus'); afterBuyInput.style.pointerEvents = 'auto'; } } xhr.send(params); } }); afterBuyPlusButton.addEventListener('click', function(){ const params = new URLSearchParams(); params.set('id', key); const xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/add'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { console.warn('offerCardMobileAfterBuyCounter MinusClick ajax error'); }else{ const response = xhr.response; //dynamic data from cart let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); ++afterBuyInput.placeholder; afterBuyCustomInput.placeholder = afterBuyInput.placeholder; afterBuyCustomInput.value = afterBuyInput.placeholder; checkAvailabilityBeforeClick(); } } xhr.send(params); }); afterBuyInput.addEventListener('click', function(){ quantityParent.style.display = 'none'; quantityCustomParent.style.display = 'flex'; const afterBuyCustomQuantityInput = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__custom-input'); const afterBuyCustomQuantityBackBtn = parentBuyBlockDesktop.querySelector('.desktop-buy-quantity__back-btn'); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyInput.placeholder); afterBuyCustomQuantityInput.value = afterBuyInput.placeholder; afterBuyCustomQuantityInput.focus(); afterBuyCustomQuantityInput.addEventListener('input', function updateCustomInputValue(e){ const afterBuyCustomQuantityInputValue = afterBuyCustomQuantityInput.value; if(Number(afterBuyCustomQuantityInput.value) < Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ МЕНЬШЕ ОСТАТКА осталось ${availability} штук ТОВАР ДОБАВЛЯЕМ`); localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); }else if(Number(afterBuyCustomQuantityInput.value) >= Number(availability)){ // console.warn(`КАСТОМНЫЙ ИНПУТ БОЛЬШЕ ИЛИ РАВЕН ОСТАТКУ осталось ${availability} штук ТОВАР НЕ ДОБАВЛЯЕМ`); offerCardAvailableSign.classList.add('desktop-description__shop--alert'); function offerCardAvailableSignAlertDisapear(){ offerCardAvailableSign.classList.remove('desktop-description__shop--alert'); } setTimeout(offerCardAvailableSignAlertDisapear, 7000); afterBuyCustomQuantityInput.value = availability; localStorage.setItem('noModalCustomQuantityInputValue', availability); }else if(availability === 'много' || availability === 'В наличии' || availability === 'По запросу'){ localStorage.setItem('noModalCustomQuantityInputValue', afterBuyCustomQuantityInputValue); } }); afterBuyCustomQuantityBackBtn.addEventListener('click', function(){ quantityCustomParent.style.display = 'none'; quantityParent.style.display = 'flex'; }); }); afterBuyQuantityBuyButton.addEventListener('click', function(e){ e.preventDefault(); let noModalCustomQuantityInputValue = localStorage.getItem('noModalCustomQuantityInputValue'); if(noModalCustomQuantityInputValue == ''){ // console.warn('noModalCustomQuantityInputValue === empty string'); }else{ // console.warn('noModalCustomQuantityInputValue'); // console.warn(noModalCustomQuantityInputValue); let thisBtn = this; thisBtn.classList.remove('desktop-buy-quantity__buy-btn'); thisBtn.classList.add('desktop-buy-quantity__buy-btn--load'); thisBtn.innerHTML = `<div class="desktop-custom-quantity-buy__buy-btn-preloader"></div>`; function sendOfferToCartDesktopCustomQuamnity(){ const params = new URLSearchParams(); params.set('id', key); params.append('qty', noModalCustomQuantityInputValue); let xhr = new XMLHttpRequest(); xhr.open('POST', '/cart/change'); xhr.responseType = 'json'; xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); xhr.onload = () => { if (xhr.status !== 200) { // console.warn('modalCustomQuantityBuyButtonMech ajax error'); } else { // console.warn('modalCustomQuantityBuyButtonMech ajax SUCCESS'); thisBtn.classList.remove('desktop-buy-quantity__buy-btn--load'); thisBtn.classList.add('desktop-buy-quantity__buy-btn'); thisBtn.innerHTML = ` `; // dynamic data from cart const response = xhr.response; let countFromCart = response.count; cartBtnDesktopMainHeaderSpan.style.visibility = 'visible'; cartBtnDesktopMainHeaderSpan.innerText = countFromCart; stickyHeaderDesktopCartCountUpdate(); trackCartCount(); afterBuyInput.placeholder = noModalCustomQuantityInputValue; quantityParent.style.display = 'flex'; quantityCustomParent.style.display = 'none'; checkAvailabilityBeforeClick(); } } xhr.send(params); } setTimeout(sendOfferToCartDesktopCustomQuamnity, 300); } }); //init parent + add tooltip offerCardDesktopBuyModalLocalStorageSwitcherHide(); } } } } xhr.send(params); } setTimeout(function(){ sendOfferToCart(); }, 400); }); } } } } singleOfferVendorPageBuyButtonMechDesktop(); //share btn copy link function shareBtnCopyLink(){ const modalShareBtn = document.querySelector('.modal-share__btn'); if(modalShareBtn){ const modalShareParent = document.querySelector('.modal-share__id-field'); const modalShareLink = document.querySelector('.modal-share__output'); //remove after adding to back let copyTip = document.createElement('div'); copyTip.classList.add('modal-share__copy-tip'); copyTip.innerHTML = `Ссылка скопирована! <span>✓</span>`; modalShareParent.appendChild(copyTip); modalShareBtn.addEventListener('click', function(){ // console.warn(modalShareLink.innerHTML); navigator.clipboard.writeText(modalShareLink.innerHTML); copyTip.style.visibility = 'visible'; setTimeout(delayDisapear, 3333); }); function delayDisapear(){ copyTip.style.visibility = 'hidden'; } } } shareBtnCopyLink() function slider() { const slidersList = document.querySelectorAll('.slider'); if (slidersList === null) { // console.log("Slider left html"); } else { for(let i = 0; i < slidersList.length; i++){ let slideIndex = 1, slides = slidersList[i].querySelectorAll('.slider__item'), dotsWrap = slidersList[i].querySelector('.slider__dots'), dots = slidersList[i].querySelectorAll('.dot'); const currentSlider = slidersList[i]; const autoScrollTimer = currentSlider.dataset.timer; showSlides(slideIndex); function showSlides(n) { if (n > slides.length) { slideIndex = 1; } if (n < 1) { slideIndex = slides.length; } slides.forEach((item) => item.style.display = 'none'); // for (var i = 0; i < slides.length; i++) { // slides[i].style.display = 'none'; // } dots.forEach((item) => item.classList.remove('dot-active')); slides[slideIndex - 1].style.display = 'block'; dots[slideIndex - 1].classList.add('dot-active'); } function plusSlides(n) { showSlides(slideIndex += n); } function currentSlide(n) { showSlides(slideIndex = n); } // function plusAutoSlides(n) { // showSlides(slideIndex += 1); // } // if(Number(autoScrollTimer) <= 0 || autoScrollTimer === null){ // console.warn('data-timer 0 or less') // }else{ // window.sliderTimer = setInterval(plusAutoSlides, Number(autoScrollTimer)); // currentSlider.addEventListener('mouseenter', function(){ // // console.warn('СЛАЙДЕР, ПРИКАЗЫВАЮ ТЕБЕ, ЗАМРИ!!!') // clearInterval(window.sliderTimer); // }); // currentSlider.addEventListener('mouseleave', function(){ // // console.warn('СЛАЙДЕР, ОТОМРИ, ОКАЯНЫЙ!!!') // window.sliderTimer = setInterval(plusAutoSlides, Number(autoScrollTimer)); // }); // } //click on dots dotsWrap.addEventListener('click', function(event) { for (let i = 0; i < dots.length + 1; i++) { if (event.target.classList.contains('dot') && event.target == dots[i-1]) { currentSlide(i); } } }); } } } slider(); function videoInBubbleSlider(){ let bubbleVideos = document.querySelectorAll('.slider__item-video'); if (bubbleVideos === null) { // console.log("sliderVideos left HTML"); } else { for (let i = 0; i < bubbleVideos.length; i++) { setupVideo(bubbleVideos[i]); } function setupVideo(bubbleVideos) { let link = bubbleVideos.querySelector('.slider__item-video-link'); let media = bubbleVideos.querySelector('.slider__item-video-media'); let button = bubbleVideos.querySelector('.slider__item-video-button'); let id = parseMediaURL(media); bubbleVideos.addEventListener('click', () => { let iframe = createIframe(id); link.remove(); button.remove(); bubbleVideos.appendChild(iframe); link.removeAttribute('href'); bubbleVideos.classList.add('bubbleVideo--enabled'); videoControlBubble(); }); } function parseMediaURL(media) { let regexp = /https:\/\/i\.ytimg\.com\/vi\/([a-zA-Z0-9_-]+)\/maxresdefault\.jpg/i; let url = media.src; let match = url.match(regexp); return match[1]; } function createIframe(id) { let iframe = document.createElement('iframe'); iframe.setAttribute('allowfullscreen', ''); iframe.setAttribute('allow', 'autoplay'); iframe.setAttribute('src', generateURL(id)); iframe.classList.add('bubbleVideo__media'); iframe.setAttribute("id", "bubbleVideo"); return iframe; } function generateURL(id) { let query = '?rel=0&showinfo=0&autoplay=1&enablejsapi=1'; return 'https://www.youtube.com/embed/' + id + query; } } } videoInBubbleSlider() function videoControlBubble(){ // console.warn('videoCntrl function'); let iframes = document.querySelectorAll('iframe'); // console.log(iframes); let dotsWrap = document.querySelectorAll('.slider__dots'); dotsWrap.forEach(item => { item.addEventListener('click', function(){ console.warn('BAM!!'); let pauseAllYouTubeVideos = () => { let iframes = document.querySelectorAll('iframe'); Array.prototype.forEach.call(iframes, iframe => { iframe.contentWindow.postMessage(JSON.stringify({ event: 'command', func: 'pauseVideo' }), '*'); }); } pauseAllYouTubeVideos(); }); }); window.addEventListener('scroll', function(){ let pauseAllYouTubeVideos = () => { let iframes = document.querySelectorAll('iframe'); Array.prototype.forEach.call(iframes, iframe => { iframe.contentWindow.postMessage(JSON.stringify({ event: 'command', func: 'pauseVideo' }), '*'); }); } pauseAllYouTubeVideos(); }); } // toogle hidding menu button function toggleHiddenMenuBtn(){ let hiddenMenuBtn = document.querySelector('.hidden-btn__icon'); let hiddenMenu = document.querySelector('.user-wrapper__hidden-menu'); let header = document.querySelector('.header'); let body = document.querySelector('body'); if(hiddenMenuBtn){ let glassBackground = document.createElement("div"); glassBackground.classList.add('header-blur-wrap'); header.after(glassBackground); hiddenMenuBtn.addEventListener('click', function() { this.classList.toggle('active'); hiddenMenu.classList.toggle('hidden-menu--on'); glassBackground.classList.toggle('header-blur-wrap--on'); body.classList.toggle('page-body__no-scroll'); }); glassBackground.addEventListener('click', function(){ hiddenMenuBtn.classList.remove('active'); hiddenMenu.classList.remove('hidden-menu--on'); glassBackground.classList.remove('header-blur-wrap--on'); body.classList.remove('page-body__no-scroll'); }); //close blocks on document cliks function handleClick(event) { const target = event.target; const isClickedOnExcludedBlock = target.matches('.hidden-btn__icon, .hb-line, .hidden-menu__link a, .hidden-menu__call-btn, .user-wrapper__hidden-menu'); if (!isClickedOnExcludedBlock) { // Handle the click event here for clicks outside the excluded blocks hiddenMenuBtn.classList.remove('active'); hiddenMenu.classList.remove('hidden-menu--on'); glassBackground.classList.remove('header-blur-wrap--on'); body.classList.remove('page-body__no-scroll'); } } document.addEventListener('click', handleClick); } } toggleHiddenMenuBtn(); //toogle search form function headerSearchToogleMobile(){ const searchBtnHeader = document.querySelector('.user-mobile__search-btn'); const searchForm = document.querySelector('.search-mobile'); if(searchBtnHeader && searchForm){ searchBtnHeader.addEventListener('click', function(){ searchForm.classList.toggle('search-mobile--on'); }); document.addEventListener('click', function(e){ if(!searchBtnHeader.contains(e.target) && !searchForm.contains(e.target)){ searchForm.classList.remove('search-mobile--on'); } }); } } headerSearchToogleMobile() //ContactUsModalOpener function headerContactUsModal() { let mainHeader = document.querySelector('.header'); if (mainHeader) { let contactUsModal = document.querySelector('.header-contact-us'); let contactUsModalWrapper = document.querySelector('.header-contact-us__wrapper'); let contactUsModalClose = document.querySelector('.header-contact-us__close'); let footerCallBtn = document.querySelector('.footer-panel__button'); let contactUsDesktopHeaderNumbers = document.querySelectorAll('.contacts__number'); let contactUsDesktopHeaderNumbersSticky = document.querySelectorAll('.sticky-header-desktop__number'); let contactUsHeaderMobileHidden = document.querySelector('.hidden-menu__call-btn'); let contactUsHeaderGlassBack = document.querySelector('.header-contact-us__blur'); let body = document.querySelector('body'); function openContactUsModal(e) { if (e) e.preventDefault(); contactUsModal.style.display = 'block'; body.classList.add('page-body__no-scroll'); contactUsModalWrapper.classList.add('header-contact-us__wrapper--opening'); } function closeContactUsModal() { contactUsModalWrapper.classList.remove('header-contact-us__wrapper--opening'); contactUsModalWrapper.classList.add('header-contact-us__wrapper--closing'); const handleAnimationEnd = function() { contactUsModal.style.display = 'none'; body.classList.remove('page-body__no-scroll'); contactUsModalWrapper.classList.remove('header-contact-us__wrapper--closing'); contactUsModalWrapper.removeEventListener('animationend', handleAnimationEnd); }; contactUsModalWrapper.addEventListener('animationend', handleAnimationEnd); } if (contactUsModal && contactUsModalClose) { contactUsDesktopHeaderNumbers.forEach(number => number.addEventListener('click', openContactUsModal)); contactUsDesktopHeaderNumbersSticky.forEach(number => number.addEventListener('click', openContactUsModal)); contactUsHeaderMobileHidden.addEventListener('click', openContactUsModal); contactUsModalClose.addEventListener('click', closeContactUsModal); contactUsHeaderGlassBack.addEventListener('click', closeContactUsModal); if (footerCallBtn) { footerCallBtn.addEventListener('click', openContactUsModal); } } else { console.log('No Header modal on the page'); } } } headerContactUsModal(); //Green navigation arrow mech function navArrowMech(){ let navLeftArrow = document.querySelector('.navigation__arrow-left'); let navRightArrow = document.querySelector('.navigation__arrow-right'); let navFirstItem = document.querySelector('.navigation__nav-item'); let navItemsList = document.querySelectorAll('.navigation__nav-item'); let navItemsListParent = document.querySelector('.navigation__nav-list'); if(navLeftArrow === null || navRightArrow === null || navFirstItem === null){ // console.log('no navigation on the page'); }else{ let lastItem = navItemsList[navItemsList.length - 1]; let intViewportWidth = window.innerWidth; // console.warn(intViewportWidth); if(intViewportWidth > 1140){ let coordOfLastItem = lastItem.getBoundingClientRect(); if(coordOfLastItem.right > intViewportWidth){ // console.warn('last item out of viewport'); navRightArrow.style.display = 'block'; navRightArrow.addEventListener('click', function(){ lastItem.scrollIntoView({ block: 'end', behavior: 'smooth' }); navRightArrow.style.display = 'none'; navLeftArrow.style.display = 'block'; }); navLeftArrow.addEventListener('click', function(){ navFirstItem.scrollIntoView({ block: 'end', inline: 'end', behavior: 'smooth' }); navLeftArrow.style.display = 'none'; navRightArrow.style.display = 'block'; }); } else{ console.warn('last item in viewport'); let summ = 0; for(let i = 0; i < navItemsList.length; i++){ summ += navItemsList[i].offsetWidth; } let summPlusPl = summ + 550; // console.log('sum of items width ' + summPlusPl + 'px'); // console.log(intViewportWidth); if(intViewportWidth > summPlusPl ){ navItemsListParent.style.justifyContent = 'flex-end'; navItemsListParent.style.paddingRight = '40px'; navRightArrow.style.display = 'none'; navLeftArrow.style.display = 'none'; } } } else { console.warn('mobile viewport'); } } } //dadataHeaderCity init; function dadataModalSuccessInit(){ //check lacalStorage parametr dadataModalSuccessConfirmCity which contain chosen city const dadataModalSuccessConfirmCity = localStorage.getItem('dadataModalSuccessConfirmCity'); if(dadataModalSuccessConfirmCity){ //if dadataModalSuccessConfirmCity is available let userLocationHeader = document.querySelector('.search-panel__user-location span'); if(userLocationHeader){ let userLocationHeaderMobile = document.querySelector('.search-panel-mobile__user-location span'); userLocationHeader.classList.add('search-panel__user-location--confirm-location'); userLocationHeader.innerText = dadataModalSuccessConfirmCity; userLocationHeaderMobile.classList.add('search-panel__user-location--confirm-location'); userLocationHeaderMobile.innerText = dadataModalSuccessConfirmCity; }else{ let userLocationCartHeader = document.querySelector('.header-cart-desktop__user-location span'); let userLocationCartHeaderMobile = document.querySelector('.header-cart-mobile__user-location span'); userLocationCartHeader.classList.add('search-panel__user-location--confirm-location'); userLocationCartHeader.innerText = dadataModalSuccessConfirmCity; userLocationCartHeaderMobile.classList.add('search-panel__user-location--confirm-location'); userLocationCartHeaderMobile.innerText = dadataModalSuccessConfirmCity; } dadataPopUpsDesktopGenerate(); dadataPopUpsMobileGenerate(); dadataPopUpsCartDesktopGenerate(); dadataPopUpsCartMobileGenerate(); setTimeout(dadataAutoCity, 2000); }else{ //if dadataModalSuccessConfirmCity NOT available console.warn('dadataModalSuccessConfirmCity NO PARAMS'); dadataHeaderCity(); } } dadataModalSuccessInit(); //Dadata header current IP and City func function dadataHeaderCity(){ const currentIp = fetch('https://ipwho.is/') .then((responce) => responce.json()) .then((data) => { const currentIpResult = data.ip const currentIpCountry = data.country let url = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/iplocate/address?ip="; let token = "7d7a4b089cea1b122a5a6e748afc75458f420444"; let query = currentIpResult; let options = { method: "GET", mode: "cors", headers: { "Content-Type": "application/json", "Accept": "application/json", "Authorization": "Token " + token } } if(currentIpCountry === 'Russia'){ fetch(url + query, options) .then(response => response.json()) .then((result) => { // console.log(result.location.data.city) const currentCity = result.location.data.city //First - cart, second - default let userLocationCartHeader = document.querySelector('.header-cart-desktop__user-location span'); let userLocationCartHeaderMobile = document.querySelector('.header-cart-mobile__user-location span'); if(userLocationCartHeader){ userLocationCartHeader.classList.add('search-panel__user-location--ask-fadeInOut-span'); userLocationCartHeaderMobile.classList.add('search-panel__user-location--ask-fadeInOut-span'); userLocationCartHeader.innerText = currentCity; userLocationCartHeaderMobile.innerText = currentCity; dadataPopUpsCartDesktopGenerate(); dadataPopUpsCartMobileGenerate(); setTimeout(dadataAutoCity, 2000); }else{ let userLocationHeader = document.querySelector('.search-panel__user-location span'); let userLocationHeaderMobile = document.querySelector('.search-panel-mobile__user-location span'); if (userLocationHeader) { userLocationHeader.classList.add('search-panel__user-location--ask-fadeInOut-span'); userLocationHeaderMobile.classList.add('search-panel__user-location--ask-fadeInOut-span'); userLocationHeader.innerText = currentCity; userLocationHeaderMobile.innerText = currentCity; //DESKTOP WAY OUT dadataPopUpsDesktopGenerate(); dadataPopUpsMobileGenerate(); setTimeout(dadataAutoCity, 2000); } } }) .catch(error => { console.warn(error); }); }else{ console.warn('ВЫ НАХОДИТЕСЬ ЗА ПРЕДЕЛАМИ РФ!'); //First - cart, second - default let userLocationCartHeader = document.querySelector('.header-cart-desktop__user-location span'); let userLocationCartHeaderMobile = document.querySelector('.header-cart-mobile__user-location span'); if(userLocationCartHeader){ userLocationCartHeader.classList.add('search-panel__user-location--ask-fadeInOut-span'); userLocationCartHeaderMobile.classList.add('search-panel__user-location--ask-fadeInOut-span'); userLocationCartHeader.innerText = 'Москва'; userLocationCartHeaderMobile.innerText = 'Москва'; dadataPopUpsCartDesktopGenerate(); dadataPopUpsCartMobileGenerate(); setTimeout(dadataAutoCity, 2000); }else{ let userLocationHeader = document.querySelector('.search-panel__user-location span'); let userLocationHeaderMobile = document.querySelector('.search-panel-mobile__user-location span'); if (userLocationHeader) { userLocationHeader.classList.add('search-panel__user-location--ask-fadeInOut-span'); userLocationHeaderMobile.classList.add('search-panel__user-location--ask-fadeInOut-span'); userLocationHeader.innerText = 'Москва'; userLocationHeaderMobile.innerText = 'Москва'; //DESKTOP WAY OUT dadataPopUpsDesktopGenerate(); dadataPopUpsMobileGenerate(); setTimeout(dadataAutoCity, 2000); } } } }); } //generate dadata pop-ups default desktop function dadataPopUpsDesktopGenerate(){ let userLocationHeader = document.querySelector('.search-panel__user-location span'); if(userLocationHeader){ //calculate position of header location block let userLocationHeaderText = userLocationHeader.innerText; let userLocationHeaderTextFromStorageChosenCity = localStorage.getItem('dadataModalSuccessConfirmCity'); if(userLocationHeaderTextFromStorageChosenCity === null){ //generate success pop-ups without saved city let dadataModalSuccess = document.createElement('div'); dadataModalSuccess.classList.add('search-panel__user-location--dadataModalSuccess'); dadataModalSuccess.innerHTML = ` <div class="search-panel__user-location--dadataModalSuccess-wrapper"> <div class="search-panel__user-location--dadataModalSuccess-question"> Ваш город ${userLocationHeaderText}? </div> <div class="search-panel__user-location--dadataModalSuccess-inner"> <div class="search-panel__user-location--dadataModalSuccess-confirmBtn">Все верно!</div> <div class="search-panel__user-location--dadataModalSuccess-anotherCity">Выбрать город</div> </div> </div> `; userLocationHeader.after(dadataModalSuccess); }else{ //generate success pop-ups let userLocationHeaderTextFromStorageChosenCityFresh = localStorage.getItem('dadataModalSuccessConfirmCity'); let dadataModalSuccess = document.createElement('div'); dadataModalSuccess.classList.add('search-panel__user-location--dadataModalSuccess'); dadataModalSuccess.innerHTML = ` <div class="search-panel__user-location--dadataModalSuccess-wrapper"> <div class="search-panel__user-location--dadataModalSuccess-question"> Ваш город ${userLocationHeaderTextFromStorageChosenCityFresh}? </div> <div class="search-panel__user-location--dadataModalSuccess-inner"> <div class="search-panel__user-location--dadataModalSuccess-confirmBtn">Все верно!</div> <div class="search-panel__user-location--dadataModalSuccess-anotherCity">Выбрать город</div> </div> </div> `; userLocationHeader.after(dadataModalSuccess); } //generate find pop-ups let dadataModalFind = document.createElement('div'); dadataModalFind.classList.add('search-panel__user-location--dadataModalFind'); dadataModalFind.innerHTML = ` <div class="search-panel__user-location--dadataModalFind-wrapper"> <img src="/img/search-icon-dadataFind.svg" alt=""> <div class="search-panel__user-location--dadataModalFind-confirmBtn"></div> <input type="text" id="dadataHeaderCity" placeholder="Введите название вашего города" autocomplete="off"> <ul class="search-panel__user-location--dadataModalFind-quickPickList"> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Москва</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Санкт-Петербург</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Новосибирск</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Екатеринбург</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Казань</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Нижний Новгород</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Челябинск</li> </ul> <a href="/pages/outside-delivery" target="_blank">*Хочу доставку в Другую страну</a> </div> `; userLocationHeader.after(dadataModalFind); const els = document.getElementsByClassName("search-panel__user-location--dadataModalFind-quickPickList"); Array.prototype.forEach.call(els, function(el) { el.addEventListener('wheel', (event) => { event.preventDefault(); el.scrollBy({ left: event.deltaY < 0 ? -30 : 30, }); }); }); //show succeess modal userLocationHeader.addEventListener('click', function(){ dadataModalSuccess.classList.toggle('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; }); //confirm city/set local storage + show find modal const dadataModalSuccess = document.querySelector('.search-panel__user-location--dadataModalSuccess'); const dadataModalSuccessQuestionBlock = document.querySelector('.search-panel__user-location--dadataModalSuccess-question'); const dadataModalSuccessConfirmBtn = document.querySelector('.search-panel__user-location--dadataModalSuccess-confirmBtn'); const dadataModalSuccessAnoterCity = document.querySelector('.search-panel__user-location--dadataModalSuccess-anotherCity'); const dadataModalFindInput = document.querySelector('.search-panel__user-location--dadataModalFind-wrapper input'); const dadataModalFindInputImg = document.querySelector('.search-panel__user-location--dadataModalFind-wrapper img'); const dadataModalFindInputConfirmBtn = document.querySelector('.search-panel__user-location--dadataModalFind-confirmBtn'); dadataModalSuccessConfirmBtn.addEventListener('click', function(){ if(userLocationHeaderTextFromStorageChosenCity === null){ localStorage.setItem('dadataModalSuccessConfirmCity', userLocationHeaderText); dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; userLocationHeader.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationHeader.classList.add('search-panel__user-location--confirm-location'); }else{ dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; userLocationHeader.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationHeader.classList.add('search-panel__user-location--confirm-location'); } }); dadataModalSuccessAnoterCity.addEventListener('click', function(){ dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'block'; }); //confirm and choose from find input dadataModalFindInput.addEventListener('click', function(){ dadataModalFindInputImg.style.display = 'none'; dadataModalFindInputConfirmBtn.style.display = 'block'; }); dadataModalFindInputConfirmBtn.addEventListener('click', function(){ const dadataModalFindInputValue = dadataModalFindInput.value; if(dadataModalFindInputValue){ userLocationHeader.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationHeader.classList.add('search-panel__user-location--confirm-location'); dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; // setTimeout(dadataPopUpsDesktopGenerateReplay, 1000); localStorage.setItem('dadataModalSuccessConfirmCity', dadataModalFindInputValue); dadataModalSuccessQuestionBlock.innerHTML = `Ваш город ${dadataModalFindInputValue}?`; userLocationHeader.innerText = dadataModalFindInputValue; }else{ //false console.warn('dadataModalFindInputValue'); console.warn(dadataModalFindInputValue); } }); //quick choose find btns const modalFindQuickChooseBtn = document.querySelectorAll('.search-panel__user-location--dadataModalFind-quickPickItem'); modalFindQuickChooseBtn.forEach(item => { const itemText = item.innerText; item.addEventListener('click', function(){ dadataModalFindInput.value = itemText; dadataModalFindInputImg.style.display = 'none'; dadataModalFindInputConfirmBtn.style.display = 'block'; }); }); //close blocks on document cliks function handleClick(event) { const target = event.target; const isClickedOnExcludedBlock = target.matches('.search-panel__user-location--confirm-location, .search-panel__user-location--dadataModalSuccess-wrapper, #dadataHeaderCity, .search-panel__user-location--dadataModalFind, .search-panel__user-location--dadataModalFind-wrapper, .search-panel__user-location--ask-fadeInOut-span, .search-panel__user-location--dadataModalSuccess-confirmBtn, .search-panel__user-location--dadataModalSuccess-anotherCity, .search-panel__user-location--dadataModalSuccess-question, .suggestions-input, .search-panel__user-location--dadataModalFind-confirmBtn, .search-panel__user-location--dadataModalFind-quickPickItem, .suggestions-wrapper, .suggestions-hint, .suggestions-value'); if (!isClickedOnExcludedBlock) { // Handle the click event here for clicks outside the excluded blocks dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; } } document.addEventListener('click', handleClick); } } //generate dadata pop-ups CART desktop function dadataPopUpsCartDesktopGenerate(){ let userLocationCartHeader = document.querySelector('.header-cart-desktop__user-location span'); if(userLocationCartHeader){ //calculate position of header location block let userLocationHeaderPosition = userLocationCartHeader.getBoundingClientRect(); let userLocationHeaderText = userLocationCartHeader.innerText; let userLocationHeaderPositionTop = parseInt(userLocationHeaderPosition.top); let userLocationHeaderPositionRight = parseInt(userLocationHeaderPosition.right); let userLocationHeaderTextFromStorageChosenCity = localStorage.getItem('dadataModalSuccessConfirmCity'); if(userLocationHeaderTextFromStorageChosenCity === null){ //generate success and find pop-ups let dadataModalSuccess = document.createElement('div'); dadataModalSuccess.classList.add('search-panel__user-location--dadataModalSuccess'); dadataModalSuccess.innerHTML = ` <div class="search-panel__user-location--dadataModalSuccess-wrapper"> <div class="search-panel__user-location--dadataModalSuccess-question"> Ваш город ${userLocationHeaderText}? </div> <div class="search-panel__user-location--dadataModalSuccess-inner"> <div class="search-panel__user-location--dadataModalSuccess-confirmBtn">Все верно!</div> <div class="search-panel__user-location--dadataModalSuccess-anotherCity">Выбрать город</div> </div> </div> `; userLocationCartHeader.after(dadataModalSuccess); }else{ //generate success and find pop-ups let userLocationHeaderTextFromStorageChosenCityFresh = localStorage.getItem('dadataModalSuccessConfirmCity'); let dadataModalSuccess = document.createElement('div'); dadataModalSuccess.classList.add('search-panel__user-location--dadataModalSuccess'); dadataModalSuccess.innerHTML = ` <div class="search-panel__user-location--dadataModalSuccess-wrapper"> <div class="search-panel__user-location--dadataModalSuccess-question"> Ваш город ${userLocationHeaderTextFromStorageChosenCityFresh}? </div> <div class="search-panel__user-location--dadataModalSuccess-inner"> <div class="search-panel__user-location--dadataModalSuccess-confirmBtn">Все верно!</div> <div class="search-panel__user-location--dadataModalSuccess-anotherCity">Выбрать город</div> </div> </div> `; userLocationCartHeader.after(dadataModalSuccess); } //generate ask and find pop-ups let dadataModalFind = document.createElement('div'); dadataModalFind.classList.add('search-panel__user-location--dadataModalFind'); dadataModalFind.innerHTML = ` <div class="search-panel__user-location--dadataModalFind-wrapper"> <img src="/img/search-icon-dadataFind.svg" alt=""> <div class="search-panel__user-location--dadataModalFind-confirmBtn"></div> <input type="text" id="dadataHeaderCity" placeholder="Введите название вашего города"> <ul class="search-panel__user-location--dadataModalFind-quickPickList"> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Москва</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Санкт-Петербург</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Новосибирск</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Екатеринбург</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Казань</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Нижний Новгород</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Челябинск</li> </ul> <a href="/pages/outside-delivery" target="_blank">*Хочу доставку в Другую страну</a> </div> `; userLocationCartHeader.after(dadataModalFind); const els = document.getElementsByClassName("search-panel__user-location--dadataModalFind-quickPickList"); Array.prototype.forEach.call(els, function(el) { el.addEventListener('wheel', (event) => { event.preventDefault(); el.scrollBy({ left: event.deltaY < 0 ? -30 : 30, }); }); }); //show succeess modal userLocationCartHeader.addEventListener('click', function(){ dadataModalSuccess.classList.toggle('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; }); //confirm city/set local storage + show find modal const dadataModalSuccess = document.querySelector('.search-panel__user-location--dadataModalSuccess'); const dadataModalSuccessQuestionBlock = document.querySelector('.search-panel__user-location--dadataModalSuccess-question'); const dadataModalSuccessConfirmBtn = document.querySelector('.search-panel__user-location--dadataModalSuccess-confirmBtn'); const dadataModalSuccessAnoterCity = document.querySelector('.search-panel__user-location--dadataModalSuccess-anotherCity'); const dadataModalFindInput = document.querySelector('.search-panel__user-location--dadataModalFind-wrapper input'); const dadataModalFindInputImg = document.querySelector('.search-panel__user-location--dadataModalFind-wrapper img'); const dadataModalFindInputConfirmBtn = document.querySelector('.search-panel__user-location--dadataModalFind-confirmBtn'); dadataModalSuccessConfirmBtn.addEventListener('click', function(){ if(userLocationHeaderTextFromStorageChosenCity === null){ localStorage.setItem('dadataModalSuccessConfirmCity', userLocationHeaderText); dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; userLocationCartHeader.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationCartHeader.classList.add('search-panel__user-location--confirm-location'); }else{ dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; userLocationCartHeader.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationCartHeader.classList.add('search-panel__user-location--confirm-location'); } }); dadataModalSuccessAnoterCity.addEventListener('click', function(){ dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'block'; }); //confirm and choose from find input dadataModalFindInput.addEventListener('click', function(){ dadataModalFindInputImg.style.display = 'none'; dadataModalFindInputConfirmBtn.style.display = 'block'; }); dadataModalFindInputConfirmBtn.addEventListener('click', function(){ const dadataModalFindInputValue = dadataModalFindInput.value; if(dadataModalFindInputValue){ // console.warn('dadataModalFindInputValue'); // console.warn(dadataModalFindInputValue); userLocationCartHeader.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationCartHeader.classList.add('search-panel__user-location--confirm-location'); dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; localStorage.setItem('dadataModalSuccessConfirmCity', dadataModalFindInputValue); dadataModalSuccessQuestionBlock.innerHTML = `Ваш город ${dadataModalFindInputValue}?`; userLocationCartHeader.innerText = dadataModalFindInputValue; }else{ //false console.warn('dadataModalFindInputValue'); console.warn(dadataModalFindInputValue); } }); //quick choose find btns const modalFindQuickChooseBtn = document.querySelectorAll('.search-panel__user-location--dadataModalFind-quickPickItem'); modalFindQuickChooseBtn.forEach(item => { const itemText = item.innerText; item.addEventListener('click', function(){ dadataModalFindInput.value = itemText; dadataModalFindInputImg.style.display = 'none'; dadataModalFindInputConfirmBtn.style.display = 'block'; }); }); //close blocks on document cliks function handleClick(event) { const target = event.target; const isClickedOnExcludedBlock = target.matches('.search-panel__user-location--confirm-location, .search-panel__user-location--dadataModalSuccess-wrapper, #dadataHeaderCity, .search-panel__user-location--dadataModalFind, .search-panel__user-location--dadataModalFind-wrapper, .search-panel__user-location--ask-fadeInOut-span, .search-panel__user-location--dadataModalSuccess-confirmBtn, .search-panel__user-location--dadataModalSuccess-anotherCity, .search-panel__user-location--dadataModalSuccess-question, .suggestions-input, .search-panel__user-location--dadataModalFind-confirmBtn, .search-panel__user-location--dadataModalFind-quickPickItem, .suggestions-wrapper, .suggestions-hint, .suggestions-value'); if (!isClickedOnExcludedBlock) { // Handle the click event here for clicks outside the excluded blocks dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; } } document.addEventListener('click', handleClick); } } //generate dadata pop-ups default Mobile function dadataPopUpsMobileGenerate(){ let userLocationHeaderMobile = document.querySelector('.search-panel-mobile__user-location span'); if(userLocationHeaderMobile){ let userLocationHeaderText = userLocationHeaderMobile.innerText; let userLocationHeaderTextFromStorageChosenCity = localStorage.getItem('dadataModalSuccessConfirmCity'); if(userLocationHeaderTextFromStorageChosenCity === null){ //generate success and find pop-ups let dadataModalSuccess = document.createElement('div'); dadataModalSuccess.classList.add('search-panel__user-location--dadataModalSuccess'); dadataModalSuccess.innerHTML = ` <div class="search-panel__user-location--dadataModalSuccess-wrapper"> <div class="search-panel__user-location--dadataModalSuccess-question"> Ваш город ${userLocationHeaderText}? </div> <div class="search-panel__user-location--dadataModalSuccess-inner"> <div class="search-panel__user-location--dadataModalSuccess-confirmBtn">Все верно!</div> <div class="search-panel__user-location--dadataModalSuccess-anotherCity">Выбрать город</div> </div> </div> `; userLocationHeaderMobile.after(dadataModalSuccess); }else{ //generate success and find pop-ups let userLocationHeaderTextFromStorageChosenCityFresh = localStorage.getItem('dadataModalSuccessConfirmCity'); let dadataModalSuccess = document.createElement('div'); dadataModalSuccess.classList.add('search-panel__user-location--dadataModalSuccess'); dadataModalSuccess.innerHTML = ` <div class="search-panel__user-location--dadataModalSuccess-wrapper"> <div class="search-panel__user-location--dadataModalSuccess-question"> Ваш город ${userLocationHeaderTextFromStorageChosenCityFresh}? </div> <div class="search-panel__user-location--dadataModalSuccess-inner"> <div class="search-panel__user-location--dadataModalSuccess-confirmBtn">Все верно!</div> <div class="search-panel__user-location--dadataModalSuccess-anotherCity">Выбрать город</div> </div> </div> `; userLocationHeaderMobile.after(dadataModalSuccess); } //generate ask and find pop-ups let dadataModalFind = document.createElement('div'); dadataModalFind.classList.add('search-panel__user-location--dadataModalFind'); dadataModalFind.innerHTML = ` <div class="search-panel__user-location--dadataModalFind-wrapper"> <img src="/img/search-icon-dadataFind.svg" alt=""> <div class="search-panel__user-location--dadataModalFind-confirmBtn"></div> <input type="text" autocomplete="off" id="dadataHeaderCityMobile" placeholder="Введите название вашего города" > <ul class="search-panel__user-location--dadataModalFind-quickPickList"> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Москва</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Санкт-Петербург</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Новосибирск</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Екатеринбург</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Казань</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Нижний Новгород</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Челябинск</li> </ul> <a href="/pages/outside-delivery" target="_blank">*Хочу доставку в Другую страну</a> </div> `; userLocationHeaderMobile.after(dadataModalFind); //show succeess modal userLocationHeaderMobile.addEventListener('click', function(){ dadataModalSuccess.classList.toggle('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; }); //confirm city/set local storage + show find modal const dadataModalSuccess = document.querySelector('.search-panel__user-location--dadataModalSuccess'); const dadataModalSuccessQuestionBlock = document.querySelector('.search-panel__user-location--dadataModalSuccess-question'); const dadataModalSuccessConfirmBtn = document.querySelector('.search-panel__user-location--dadataModalSuccess-confirmBtn'); const dadataModalSuccessAnoterCity = document.querySelector('.search-panel__user-location--dadataModalSuccess-anotherCity'); const dadataModalFindInput = document.querySelector('.search-panel__user-location--dadataModalFind-wrapper input'); const dadataModalFindInputImg = document.querySelector('.search-panel__user-location--dadataModalFind-wrapper img'); const dadataModalFindInputConfirmBtn = document.querySelector('.search-panel__user-location--dadataModalFind-confirmBtn'); dadataModalSuccessConfirmBtn.addEventListener('click', function(){ if(userLocationHeaderTextFromStorageChosenCity === null){ localStorage.setItem('dadataModalSuccessConfirmCity', userLocationHeaderText); dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; userLocationHeaderMobile.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationHeaderMobile.classList.add('search-panel__user-location--confirm-location'); }else{ dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; userLocationHeaderMobile.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationHeaderMobile.classList.add('search-panel__user-location--confirm-location'); } }); dadataModalSuccessAnoterCity.addEventListener('click', function(){ dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'block'; }); //confirm and choose from find input dadataModalFindInput.addEventListener('click', function(){ dadataModalFindInputImg.style.display = 'none'; dadataModalFindInputConfirmBtn.style.display = 'block'; }); dadataModalFindInputConfirmBtn.addEventListener('click', function(){ const dadataModalFindInputValue = dadataModalFindInput.value; if(dadataModalFindInputValue){ userLocationHeaderMobile.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationHeaderMobile.classList.add('search-panel__user-location--confirm-location'); dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; dadataModalSuccessQuestionBlock.innerHTML = `Ваш город ${dadataModalFindInputValue}?`; localStorage.setItem('dadataModalSuccessConfirmCity', dadataModalFindInputValue); userLocationHeaderMobile.innerText = dadataModalFindInputValue; }else{ //false console.warn('dadataModalFindInputValue'); console.warn(dadataModalFindInputValue); } }); //quick choose find btns const modalFindQuickChooseBtn = document.querySelectorAll('.search-panel__user-location--dadataModalFind-quickPickItem'); modalFindQuickChooseBtn.forEach(item => { const itemText = item.innerText; item.addEventListener('click', function(){ dadataModalFindInput.value = itemText; dadataModalFindInputImg.style.display = 'none'; dadataModalFindInputConfirmBtn.style.display = 'block'; }); }); function handleClick(event) { const target = event.target; const isClickedOnExcludedBlock = target.matches('.search-panel__user-location--confirm-location, .search-panel__user-location--dadataModalSuccess-wrapper, #dadataHeaderCity, .search-panel__user-location--dadataModalFind, .search-panel__user-location--dadataModalFind-wrapper, .search-panel__user-location--ask-fadeInOut-span, .search-panel__user-location--dadataModalSuccess-confirmBtn, .search-panel__user-location--dadataModalSuccess-anotherCity, .search-panel__user-location--dadataModalSuccess-question, .suggestions-input, .search-panel__user-location--dadataModalFind-confirmBtn, .search-panel__user-location--dadataModalFind-quickPickItem, .suggestions-wrapper, .suggestions-hint, .suggestions-value'); if (!isClickedOnExcludedBlock) { // Handle the click event here for clicks outside the excluded blocks dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; } } document.addEventListener('click', handleClick); } } //generate dadata pop-ups cart desktop function dadataPopUpsCartMobileGenerate(){ let userLocationCartHeaderMobile = document.querySelector('.header-cart-mobile__user-location span'); if(userLocationCartHeaderMobile){ let userLocationHeaderText = userLocationCartHeaderMobile.innerText; let userLocationHeaderTextFromStorageChosenCity = localStorage.getItem('dadataModalSuccessConfirmCity'); if(userLocationHeaderTextFromStorageChosenCity === null){ //generate success and find pop-ups let dadataModalSuccess = document.createElement('div'); dadataModalSuccess.classList.add('search-panel__user-location--dadataModalSuccess'); dadataModalSuccess.innerHTML = ` <div class="search-panel__user-location--dadataModalSuccess-wrapper"> <div class="search-panel__user-location--dadataModalSuccess-question"> Ваш город ${userLocationHeaderText}? </div> <div class="search-panel__user-location--dadataModalSuccess-inner"> <div class="search-panel__user-location--dadataModalSuccess-confirmBtn">Все верно!</div> <div class="search-panel__user-location--dadataModalSuccess-anotherCity">Выбрать город</div> </div> </div> `; userLocationCartHeaderMobile.after(dadataModalSuccess); }else{ //generate success and find pop-ups let userLocationHeaderTextFromStorageChosenCityFresh = localStorage.getItem('dadataModalSuccessConfirmCity'); let dadataModalSuccess = document.createElement('div'); dadataModalSuccess.classList.add('search-panel__user-location--dadataModalSuccess'); dadataModalSuccess.innerHTML = ` <div class="search-panel__user-location--dadataModalSuccess-wrapper"> <div class="search-panel__user-location--dadataModalSuccess-question"> Ваш город ${userLocationHeaderTextFromStorageChosenCityFresh}? </div> <div class="search-panel__user-location--dadataModalSuccess-inner"> <div class="search-panel__user-location--dadataModalSuccess-confirmBtn">Все верно!</div> <div class="search-panel__user-location--dadataModalSuccess-anotherCity">Выбрать город</div> </div> </div> `; userLocationCartHeaderMobile.after(dadataModalSuccess); } //generate ask and find pop-ups let dadataModalFind = document.createElement('div'); dadataModalFind.classList.add('search-panel__user-location--dadataModalFind'); dadataModalFind.innerHTML = ` <div class="search-panel__user-location--dadataModalFind-wrapper"> <img src="/img/search-icon-dadataFind.svg" alt=""> <div class="search-panel__user-location--dadataModalFind-confirmBtn"></div> <input type="text" id="dadataHeaderCityMobile" placeholder="Введите название вашего города"> <ul class="search-panel__user-location--dadataModalFind-quickPickList"> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Москва</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Санкт-Петербург</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Новосибирск</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Екатеринбург</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Казань</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Нижний Новгород</li> <li class="search-panel__user-location--dadataModalFind-quickPickItem">Челябинск</li> </ul> <a href="/pages/outside-delivery" target="_blank">*Хочу доставку в Другую страну</a> </div> `; userLocationCartHeaderMobile.after(dadataModalFind); const els = document.getElementsByClassName("search-panel__user-location--dadataModalFind-quickPickList"); Array.prototype.forEach.call(els, function(el) { el.addEventListener('wheel', (event) => { event.preventDefault(); el.scrollBy({ left: event.deltaY < 0 ? -30 : 30, }); }); }); //show succeess modal userLocationCartHeaderMobile.addEventListener('click', function(){ dadataModalSuccess.classList.toggle('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; }); //confirm city/set local storage + show find modal const dadataModalSuccess = document.querySelector('.search-panel__user-location--dadataModalSuccess'); const dadataModalSuccessQuestionBlock = document.querySelector('.search-panel__user-location--dadataModalSuccess-question'); const dadataModalSuccessConfirmBtn = document.querySelector('.search-panel__user-location--dadataModalSuccess-confirmBtn'); const dadataModalSuccessAnoterCity = document.querySelector('.search-panel__user-location--dadataModalSuccess-anotherCity'); const dadataModalFindInput = document.querySelector('.search-panel__user-location--dadataModalFind-wrapper input'); const dadataModalFindInputImg = document.querySelector('.search-panel__user-location--dadataModalFind-wrapper img'); const dadataModalFindInputConfirmBtn = document.querySelector('.search-panel__user-location--dadataModalFind-confirmBtn'); dadataModalSuccessConfirmBtn.addEventListener('click', function(){ if(userLocationHeaderTextFromStorageChosenCity === null){ localStorage.setItem('dadataModalSuccessConfirmCity', userLocationHeaderText); dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; userLocationCartHeaderMobile.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationCartHeaderMobile.classList.add('search-panel__user-location--confirm-location'); }else{ dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; userLocationCartHeaderMobile.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationCartHeaderMobile.classList.add('search-panel__user-location--confirm-location'); } }); dadataModalSuccessAnoterCity.addEventListener('click', function(){ dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'block'; }); //confirm and choose from find input dadataModalFindInput.addEventListener('click', function(){ dadataModalFindInputImg.style.display = 'none'; dadataModalFindInputConfirmBtn.style.display = 'block'; }); dadataModalFindInputConfirmBtn.addEventListener('click', function(){ const dadataModalFindInputValue = dadataModalFindInput.value; if(dadataModalFindInputValue){ userLocationCartHeaderMobile.classList.remove('search-panel__user-location--ask-fadeInOut-span'); userLocationCartHeaderMobile.classList.add('search-panel__user-location--confirm-location'); dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; dadataModalSuccessQuestionBlock.innerHTML = `Ваш город ${dadataModalFindInputValue}?`; localStorage.setItem('dadataModalSuccessConfirmCity', dadataModalFindInputValue); userLocationCartHeaderMobile.innerText = dadataModalFindInputValue; }else{ //false console.warn('dadataModalFindInputValue'); console.warn(dadataModalFindInputValue); } }); //quick choose find btns const modalFindQuickChooseBtn = document.querySelectorAll('.search-panel__user-location--dadataModalFind-quickPickItem'); modalFindQuickChooseBtn.forEach(item => { const itemText = item.innerText; item.addEventListener('click', function(){ dadataModalFindInput.value = itemText; dadataModalFindInputImg.style.display = 'none'; dadataModalFindInputConfirmBtn.style.display = 'block'; }); }); function handleClick(event) { const target = event.target; const isClickedOnExcludedBlock = target.matches('.search-panel__user-location--confirm-location, .search-panel__user-location--dadataModalSuccess-wrapper, #dadataHeaderCity, .search-panel__user-location--dadataModalFind, .search-panel__user-location--dadataModalFind-wrapper, .search-panel__user-location--ask-fadeInOut-span, .search-panel__user-location--dadataModalSuccess-confirmBtn, .search-panel__user-location--dadataModalSuccess-anotherCity, .search-panel__user-location--dadataModalSuccess-question, .suggestions-input, .search-panel__user-location--dadataModalFind-confirmBtn, .search-panel__user-location--dadataModalFind-quickPickItem, .suggestions-wrapper, .suggestions-hint, .suggestions-value'); if (!isClickedOnExcludedBlock) { // Handle the click event here for clicks outside the excluded blocks dadataModalSuccess.classList.remove('search-panel__user-location--dadataModalSuccess-on'); dadataModalFind.style.display = 'none'; } } document.addEventListener('click', handleClick); } } //inject jQuery on page for real-time suggestion function dadataAutoCity(){ //jquery to dadata let intViewportWidth = window.innerWidth; if(intViewportWidth < 1140){ //mobile const scriptHeaderDadataJqueryMobile = document.createElement('script'); scriptHeaderDadataJqueryMobile.async = false; scriptHeaderDadataJqueryMobile.innerHTML = ` jQuery(document).ready(function($){ let token = "7d7a4b089cea1b122a5a6e748afc75458f420444"; let type = "address"; let $city = $("#dadataHeaderCityMobile"); let $address = $("#address") ; function iplocate() { let serviceUrl = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address"; let params = { type: "GET", contentType: "application/json", headers: { "Authorization": "Token " + token } }; return $.ajax(serviceUrl, params); } let defaultFormatResult = $.Suggestions.prototype.formatResult; function formatResult(value, currentValue, suggestion, options) { let newValue = suggestion.data.city; suggestion.value = newValue; return defaultFormatResult.call(this, newValue, currentValue, suggestion, options); } function formatSelected(suggestion) { return suggestion.data.city; } // город и населенный пункт $city.suggestions({ token: token, type: "ADDRESS", hint: false, bounds: "city", constraints: { locations: { city_type_full: "город" } }, formatResult: formatResult, formatSelected: formatSelected, onSelect: function(suggestion) { console.log(suggestion); } }); disableAutocomplete(); // console.warn( '$city.suggestions ') // console.warn( $city.suggestions() ) }); `; document.body.appendChild(scriptHeaderDadataJqueryMobile); }else{ //desktop const scriptHeaderDadataJquery = document.createElement('script'); scriptHeaderDadataJquery.async = false; scriptHeaderDadataJquery.innerHTML = ` jQuery(document).ready(function($){ let token = "7d7a4b089cea1b122a5a6e748afc75458f420444"; let type = "address"; let $city = $("#dadataHeaderCity"); let $address = $("#address") ; function iplocate() { let serviceUrl = "https://suggestions.dadata.ru/suggestions/api/4_1/rs/suggest/address"; let params = { type: "GET", contentType: "application/json", headers: { "Authorization": "Token " + token } }; return $.ajax(serviceUrl, params); } let defaultFormatResult = $.Suggestions.prototype.formatResult; function formatResult(value, currentValue, suggestion, options) { let newValue = suggestion.data.city; suggestion.value = newValue; return defaultFormatResult.call(this, newValue, currentValue, suggestion, options); } function formatSelected(suggestion) { return suggestion.data.city; } // город и населенный пункт $city.suggestions({ token: token, type: "ADDRESS", hint: false, bounds: "city", constraints: { locations: { city_type_full: "город" } }, formatResult: formatResult, formatSelected: formatSelected, onSelect: function(suggestion) { console.log(suggestion); } }); disableAutocomplete(); // console.warn( '$city.suggestions ') // console.warn( $city.suggestions() ) }); `; document.body.appendChild(scriptHeaderDadataJquery); } } function searchModalToggle() { const searchForm = document.querySelectorAll('form[action="/search"]'); let settingBtn, settingsModalWrapper; if (searchForm !== null) { searchForm.forEach(item => { settingBtn = item.querySelector('.toggle-settings'); if (settingBtn !== null) { settingBtn.addEventListener('click', function (e) { e.preventDefault(); settingsModalWrapper = e.target.parentElement.querySelector('.search__modal-wrapper'); settingsModalWrapper.classList.toggle("search__modal-wrapper--visible"); this.classList.toggle("search__setting--active"); }); } }); document.onclick = function (e) { searchForm.forEach(item => { settingsModalWrapper = item.querySelector('.search__modal-wrapper'); settingBtn = item.querySelector('.toggle-settings'); if (settingBtn) { if (!settingsModalWrapper.contains(e.target) && !e.target.classList.contains('toggle-settings') || e.target.classList.contains('search__modal-close')) { settingsModalWrapper.classList.remove("search__modal-wrapper--visible"); settingBtn.classList.remove("search__setting--active"); } } }); } } } searchModalToggle(); // short post tips function newsPostShortAskBtnTip(){ let askBtns = document.querySelectorAll('.news-post__short-btn--ask'); if(askBtns === null){ // console.log('no askBtns in news on the page!'); } else { for(let i = 0; i < askBtns.length; i++){ askBtns[i].addEventListener('mouseover', function(){ let currentTip = this.querySelector('.news-post__short-btn--ask-tip'); if(currentTip){ currentTip.style.visibility = 'visible'; currentTip.style.opacity = '1'; } }); askBtns[i].addEventListener('mouseout', function(){ let currentTip = this.querySelector('.news-post__short-btn--ask-tip'); if(currentTip){ currentTip.style.visibility = 'hidden'; currentTip.style.opacity = '0'; } }); } } } newsPostShortAskBtnTip(); function newsPostShortShareBtnTip(){ let shareBts = document.querySelectorAll('.news-post__short-btn--share'); if(shareBts === null){ // console.log('no shareBtns in news on the page!'); }else { for(let i = 0; i < shareBts.length; i++){ shareBts[i].addEventListener('mouseover', function(){ let currentTipNewsShare = this.querySelector('.news-post__short-btn--share-tip'); if(currentTipNewsShare){ currentTipNewsShare.style.visibility = 'visible'; currentTipNewsShare.style.opacity = '1'; } }); shareBts[i].addEventListener('mouseout', function(){ let currentTipNewsShare = this.querySelector('.news-post__short-btn--share-tip'); if(currentTipNewsShare){ currentTipNewsShare.style.visibility = 'hidden'; currentTipNewsShare.style.opacity = '0'; } }); } } } newsPostShortShareBtnTip(); // full post tips function newsPostFullAskBtnTip(){ let askBtnsFull = document.querySelectorAll('.news-post__full-btn--ask'); if(askBtnsFull === null){ // console.log('no btn in full news-post'); } else{ for(let i = 0; i < askBtnsFull.length; i++){ askBtnsFull[i].addEventListener('mouseover', function(){ let currentTipNewsAsk = this.querySelector('.news-post__full-btn--ask-tip'); if(currentTipNewsAsk){ currentTipNewsAsk.style.visibility = 'visible'; currentTipNewsAsk.style.opacity = '1'; } }); askBtnsFull[i].addEventListener('mouseout', function(){ let currentTipNewsAsk = this.querySelector('.news-post__full-btn--ask-tip'); if(currentTipNewsAsk){ currentTipNewsAsk.style.visibility = 'hidden'; currentTipNewsAsk.style.opacity = '0'; } }); } } } newsPostFullAskBtnTip(); function newsPostFullShareBtnTip(){ let shareBtnsFull = document.querySelectorAll('.news-post__full-btn--share'); if(shareBtnsFull === null){ // console.log('no share btns in full news-post'); }else { for(let i = 0; i < shareBtnsFull.length; i++){ shareBtnsFull[i].addEventListener('mouseover', function(){ let currentTipNewsShare = this.querySelector('.news-post__full-btn--share-tip'); if(currentTipNewsShare){ currentTipNewsShare.style.visibility = 'visible'; currentTipNewsShare.style.opacity = '1'; } }); shareBtnsFull[i].addEventListener('mouseout', function(){ let currentTipNewsShare = this.querySelector('.news-post__full-btn--share-tip'); if(currentTipNewsShare){ currentTipNewsShare.style.visibility = 'hidden'; currentTipNewsShare.style.opacity = '0'; } }); } } } newsPostFullShareBtnTip(); //NEWS MECH | NEWS //news open/close mech function newsPostOpen() { let newsPosts = document.querySelectorAll(".news-post"); if (newsPosts === null ) { // console.log("newsPosts left html"); } else { newsPosts.forEach(item => { let newsPostOpenBtn = item.querySelector(".news-post__short-open"); let newsPostFullPost = item.querySelector(".news-post__full"); let newsPostShortPost = item.querySelector(".news-post__short"); let newsPostShortPanel = item.querySelector(".news-post__short-panel"); let newsPostFullClose = item.querySelector(".news-post__full-close"); if (newsPostOpenBtn === null || newsPostFullPost === null || newsPostShortPost === null || newsPostShortPanel === null || newsPostFullClose === null ) { // console.log("newsPosts elements left html"); } else { let intViewportWidth = window.innerWidth; if(intViewportWidth > 1140){ let currentSliderList = newsPostFullPost.querySelectorAll('.news-post__full-slider'); currentSliderList.forEach(item => { item.classList.remove('news-post__full-slider'); item.classList.add('news-post__full-slider--closed'); }) newsPostOpenBtn.addEventListener("click", function(e) { e.preventDefault(); newsPostShortPanel.style.display = 'none'; newsPostFullPost.style.display = 'block'; //Smooth scroll to the proper position const yOffset = -90; const y = newsPostFullPost.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); // console.log(newsPostFullPost); // console.log(currentSliderList); currentSliderList.forEach(item => { item.classList.add('news-post__full-slider--active'); }) }); newsPostOpenBtn.addEventListener("click", function sliderSwitch(e) { e.preventDefault(); // console.warn("only one!"); newPostSlider(); // newPostSlider(); }, {once : true}); newsPostFullClose.addEventListener("click", function(e) { e.preventDefault(); // newsPostShortPost.scrollIntoView({behavior: "smooth"}); //Smooth scroll to the proper position const yOffset = -90; const y = newsPostShortPost.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); setTimeout(function(){ newsPostFullPost.style.display = 'none'; let intViewportWidth = window.innerWidth; if(intViewportWidth < 760){ newsPostShortPanel.style.display = 'block'; } else { newsPostShortPanel.style.display = 'flex'; } }, 600); }); }else{ let currentSliderList = newsPostFullPost.querySelectorAll('.news-post__full-slider'); currentSliderList.forEach(item => { item.classList.remove('news-post__full-slider'); item.classList.add('news-post__full-slider--closed'); }) newsPostOpenBtn.addEventListener("click", function(e) { e.preventDefault(); newsPostShortPanel.style.display = 'none'; newsPostFullPost.style.display = 'block'; //Smooth scroll to the proper position const yOffset = -5; const y = newsPostFullPost.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); // console.log(newsPostFullPost); // console.log(currentSliderList); currentSliderList.forEach(item => { item.classList.add('news-post__full-slider--active'); }) }); newsPostOpenBtn.addEventListener("click", function sliderSwitch(e) { e.preventDefault(); // console.warn("only one!"); newPostSlider(); // newPostSlider(); }, {once : true}); newsPostFullClose.addEventListener("click", function(e) { e.preventDefault(); // newsPostShortPost.scrollIntoView({behavior: "smooth"}); //Smooth scroll to the proper position const yOffset = -5; const y = newsPostShortPost.getBoundingClientRect().top + window.pageYOffset + yOffset; window.scrollTo({top: y, behavior: 'smooth'}); setTimeout(function(){ newsPostFullPost.style.display = 'none'; let intViewportWidth = window.innerWidth; if(intViewportWidth < 760){ newsPostShortPanel.style.display = 'block'; } else { newsPostShortPanel.style.display = 'flex'; } }, 600); }); } } }); } } newsPostOpen(); // Brand New Full post slider in closed card function newPostSlider(){ let slider = document.querySelectorAll('.news-post__full-slider--active'); if(slider === null){ // console.log('no news post slider on the page'); }else{ for(let i = 0; i < slider.length; i++){ let sliderItems = slider[i].querySelector('.news-post__full-slides'); let sliderSlide = slider[i].querySelectorAll('.news-post__full-slide'); let prev = slider[i].querySelector('.news-post__full-slider-control-prev'); let next = slider[i].querySelector('.news-post__full-slider-control-next'); let sliderWrapper = slider[i].querySelector('.news-post__full-slider-wrapper'); // console.log("I`m here!"); let parentOfSlider = slider[i].parentElement; let parentIsHidden = (parentOfSlider.offsetHeight === 0 && parentOfSlider.offsetWidth === 0); //More space to full slider if(parentOfSlider.classList.contains('news-post__full-block')){ let intViewportWidth = window.innerWidth; if(intViewportWidth < 499){ console.warn('i`m here! newPostSlider mobile size'); sliderWrapper.style.minHeight = "300px"; slider[i].style.minHeight = "300px"; sliderWrapper.style.maxHeight = "325px"; slider[i].style.maxHeight = "325px"; sliderSlide.forEach(item => { item.style.minHeight = "300px"; let slidePic = item.querySelector('img'); slidePic.style.height = "300px" }) }else if(intViewportWidth < 1140){ console.warn('i`m here! newPostSlider tablet size'); sliderWrapper.style.minHeight = "580px"; slider[i].style.minHeight = "630px"; sliderWrapper.style.maxHeight = "600px"; slider[i].style.maxHeight = "600px"; sliderSlide.forEach(item => { item.style.minHeight = "630px"; let slidePic = item.querySelector('img'); slidePic.style.height = "580px" }) }else{ console.warn('i`m here! newPostSlider Desktop size'); sliderWrapper.style.minHeight = "560px"; slider[i].style.minHeight = "640"; sliderWrapper.style.maxHeight = "540px"; slider[i].style.maxHeight = "640px"; sliderSlide.forEach(item => { item.style.minHeight = "560px"; }) } } //Check how many slides in slide if(sliderSlide.length === 1){ // console.warn('one slide! turn off slider'); prev.style.display = 'none'; next.style.display = 'none'; sliderSlide.forEach(item => { item.style.maxWidth = sliderWrapper.offsetWidth + "px"; }); }else { // console.warn('many slides! turn on slider') sliderItems.style.left ='-' + sliderWrapper.offsetWidth + 'px'; sliderSlide.forEach(item => { item.style.width = sliderWrapper.offsetWidth + 'px'; item.style.height = sliderWrapper.offsetHight + 'px'; // console.log(item); }) function slide(wrapper, items, prev, next) { // console.log("I`m here!"); let posX1 = 0, posX2 = 0, posInitial, posFinal, threshold = 100, slides = items.getElementsByClassName('news-post__full-slide'), slidesLength = slides.length, slideSize = items.getElementsByClassName('news-post__full-slide')[0].offsetWidth, firstSlide = slides[0], lastSlide = slides[slidesLength - 1], cloneFirst = firstSlide.cloneNode(true), cloneLast = lastSlide.cloneNode(true), index = 0, allowShift = true; // Clone first and last slide items.appendChild(cloneFirst); items.insertBefore(cloneLast, firstSlide); wrapper.classList.add('loaded'); // Click events prev.addEventListener('click', function (e) { e.preventDefault(); shiftSlide(-1); }); next.addEventListener('click', function (e) { e.preventDefault(); shiftSlide(1); }); // Transition events items.addEventListener('transitionend', checkIndex); function dragStart (e) { e = e || window.event; e.preventDefault(); posInitial = items.offsetLeft; if (e.type == 'touchstart') { posX1 = e.touches[0].clientX; } else { posX1 = e.clientX; document.onmouseup = dragEnd; document.onmousemove = dragAction; } } function dragAction (e) { e = e || window.event; if (e.type == 'touchmove') { posX2 = posX1 - e.touches[0].clientX; posX1 = e.touches[0].clientX; } else { posX2 = posX1 - e.clientX; posX1 = e.clientX; } items.style.left = (items.offsetLeft - posX2) + "px"; } function dragEnd (e) { posFinal = items.offsetLeft; if (posFinal - posInitial < -threshold) { shiftSlide(1, 'drag'); } else if (posFinal - posInitial > threshold) { shiftSlide(-1, 'drag'); } else { items.style.left = (posInitial) + "px"; } document.onmouseup = null; document.onmousemove = null; } function shiftSlide(dir, action) { items.classList.add('shifting'); if (allowShift) { if (!action) { posInitial = items.offsetLeft; } if (dir == 1) { items.style.left = (posInitial - slideSize) + "px"; index++; } else if (dir == -1) { items.style.left = (posInitial + slideSize) + "px"; index--; } }; allowShift = false; } function checkIndex (){ items.classList.remove('shifting'); if (index == -1) { items.style.left = -(slidesLength * slideSize) + "px"; index = slidesLength - 1; } if (index == slidesLength) { items.style.left = -(1 * slideSize) + "px"; index = 0; } allowShift = true; } slider[i].classList.remove('news-post__full-slider--active'); } function slideOnlyButtons(wrapper, items, prev, next) { // console.log("I`m here!"); let posX1 = 0, posX2 = 0, posInitial, posFinal, threshold = 100, slides = items.getElementsByClassName('news-post__full-slide'), slidesLength = slides.length, slideSize = items.getElementsByClassName('news-post__full-slide')[0].offsetWidth, firstSlide = slides[0], lastSlide = slides[slidesLength - 1], cloneFirst = firstSlide.cloneNode(true), cloneLast = lastSlide.cloneNode(true), index = 0, allowShift = true; // Clone first and last slide items.appendChild(cloneFirst); items.insertBefore(cloneLast, firstSlide); wrapper.classList.add('loaded'); // Click events prev.addEventListener('click', function (e) { e.preventDefault(); shiftSlide(-1); }); next.addEventListener('click', function (e) { e.preventDefault(); shiftSlide(1); }); // Transition events items.addEventListener('transitionend', checkIndex); function shiftSlide(dir, action) { items.classList.add('shifting'); if (allowShift) { if (!action) { posInitial = items.offsetLeft; } if (dir == 1) { items.style.left = (posInitial - slideSize) + "px"; index++; } else if (dir == -1) { items.style.left = (posInitial + slideSize) + "px"; index--; } }; allowShift = false; } function checkIndex (){ items.classList.remove('shifting'); if (index == -1) { items.style.left = -(slidesLength * slideSize) + "px"; index = slidesLength - 1; } if (index == slidesLength) { items.style.left = -(1 * slideSize) + "px"; index = 0; } allowShift = true; } slider[i].classList.remove('news-post__full-slider--active'); } let intViewportWidth = window.innerWidth; if(intViewportWidth < 1140){ slide(slider[i], sliderItems, prev, next); } else { slideOnlyButtons(slider[i], sliderItems, prev, next); } } } } } // Brand New Full post slider in opened card function newPostSliderSingle(){ let slider = document.querySelectorAll('.news-post__full-slider'); if(slider === null){ // console.log('no news post slider on the page'); } else{ for(let i = 0; i < slider.length; i++){ let sliderItems = slider[i].querySelector('.news-post__full-slides'); let sliderSlide = slider[i].querySelectorAll('.news-post__full-slide'); let prev = slider[i].querySelector('.news-post__full-slider-control-prev'); let next = slider[i].querySelector('.news-post__full-slider-control-next'); let sliderWrapper = slider[i].querySelector('.news-post__full-slider-wrapper'); const sliderParent = slider[i].parentElement; const dataHeightDesktopOfSlider = sliderParent.dataset.heightDesktop; const dataHeightTabletOfSlider = sliderParent.dataset.heightTablet; const dataHeightMobileOfSlider = sliderParent.dataset.heightMobile; let parentOfSlider = slider[i].parentElement; //More space to full slider function newPostSliderSingleDynamicHeight(){ // console.warn('i`m here! newPostSliderSingleDynamicHeight '); let intViewportWidth = window.innerWidth; if(intViewportWidth < 499){ // console.warn('i`m here! newPostSliderSingle mobile size'); sliderWrapper.style.minHeight = dataHeightMobileOfSlider + "px"; slider[i].style.minHeight = dataHeightMobileOfSlider + "px"; sliderWrapper.style.maxHeight = dataHeightMobileOfSlider + "px"; slider[i].style.maxHeight = dataHeightMobileOfSlider + "px"; sliderParent.style.maxHeight = dataHeightMobileOfSlider + "px"; sliderParent.style.minHeight = dataHeightMobileOfSlider + "px"; sliderSlide.forEach(item => { item.style.minHeight = dataHeightMobileOfSlider + "px"; let slidePic = item.querySelector('img'); slidePic.style.height = dataHeightMobileOfSlider + "px"; }) }else if(intViewportWidth < 1140){ // console.warn('i`m here! newPostSliderSingle tablet size'); sliderWrapper.style.minHeight = dataHeightTabletOfSlider+ "px"; slider[i].style.minHeight = dataHeightTabletOfSlider+ "px"; sliderWrapper.style.maxHeight = dataHeightTabletOfSlider+ "px"; slider[i].style.maxHeight = dataHeightTabletOfSlider+ "px"; sliderParent.style.maxHeight = dataHeightTabletOfSlider + "px"; sliderParent.style.minHeight = dataHeightTabletOfSlider + "px"; sliderSlide.forEach(item => { item.style.minHeight = dataHeightTabletOfSlider+ "px"; let slidePic = item.querySelector('img'); slidePic.style.height = dataHeightTabletOfSlider+ "px"; }) }else{ // console.warn('i`m here! newPostSliderSingle Desktpop size'); sliderWrapper.style.minHeight = dataHeightDesktopOfSlider + "px"; slider[i].style.minHeight = dataHeightDesktopOfSlider + "px"; sliderWrapper.style.maxHeight = dataHeightDesktopOfSlider + "px"; slider[i].style.maxHeight = dataHeightDesktopOfSlider + "px"; sliderParent.style.maxHeight = dataHeightDesktopOfSlider + "px"; sliderParent.style.minHeight = dataHeightDesktopOfSlider + "px"; sliderSlide.forEach(item => { item.style.minHeight = dataHeightDesktopOfSlider + "px"; }) } } newPostSliderSingleDynamicHeight() //Check how many slides in slide if(sliderSlide.length === 1){ // console.warn('one slide! turn off slider'); prev.style.display = 'none'; next.style.display = 'none'; sliderSlide.forEach(item => { item.style.maxWidth = sliderWrapper.offsetWidth + "px"; }); }else{ sliderItems.style.left ='-' + sliderWrapper.offsetWidth + 'px'; console.warn('sliderWrapper.offsetWidth') console.warn(sliderWrapper.offsetWidth) sliderSlide.forEach(item => { item.style.width = sliderWrapper.offsetWidth + 'px'; item.style.height = sliderWrapper.offsetHight + 'px'; }) function slideSingle(wrapper, items, prev, next) { let posX1 = 0, posX2 = 0, posInitial, posFinal, threshold = 100, slides = items.getElementsByClassName('news-post__full-slide'), slidesLength = slides.length, slideSize = items.getElementsByClassName('news-post__full-slide')[0].offsetWidth, firstSlide = slides[0], lastSlide = slides[slidesLength - 1], cloneFirst = firstSlide.cloneNode(true), cloneLast = lastSlide.cloneNode(true), index = 0, allowShift = true; // Clone first and last slide items.appendChild(cloneFirst); items.insertBefore(cloneLast, firstSlide); wrapper.classList.add('loaded'); // Click events prev.addEventListener('click', function (e) { e.preventDefault(); shiftSlide(-1); }); next.addEventListener('click', function (e) { e.preventDefault(); shiftSlide(1); }); // Transition events items.addEventListener('transitionend', checkIndex); function shiftSlide(dir, action) { items.classList.add('shifting'); if (allowShift) { if (!action) { posInitial = items.offsetLeft; } if (dir == 1) { items.style.left = (posInitial - slideSize) + "px"; index++; } else if (dir == -1) { items.style.left = (posInitial + slideSize) + "px"; index--; } }; allowShift = false; } function checkIndex(){ items.classList.remove('shifting'); if (index == -1) { items.style.left = -(slidesLength * slideSize) + "px"; index = slidesLength - 1; } if (index == slidesLength) { items.style.left = -(1 * slideSize) + "px"; index = 0; } allowShift = true; } slider[i].classList.remove('news-post__full-slider--active'); } slideSingle(slider[i], sliderItems, prev, next); } } } } newPostSliderSingle(); function singleUniversalSliderDetect(){ let singleUniversalSliderContainer = document.querySelectorAll('.single-universal-slider'); if(singleUniversalSliderContainer === null){ // console.log('no single post on the page'); } else{ for (let i = 0; i < singleUniversalSliderContainer.length; i++) { let sliderContainer = singleUniversalSliderContainer[i].querySelector('.news-post__full-slider'); let sliderVideoContainer = singleUniversalSliderContainer[i].querySelectorAll('.news-post__full-video'); sliderVideoContainer.forEach(item =>{ item.classList.remove('news-post__full-video'); item.classList.add('news-post__full-video--universal'); }); sliderContainer.classList.remove('news-post__full-slider'); sliderContainer.classList.add('news-post__full-slider--universal'); } } } singleUniversalSliderDetect(); //Video in slider function fullPostSliderVideoNews() { let videos = document.querySelectorAll('.news-post__full-video'); if (videos === null) { // console.log("sliderVideos left HTML"); } else { for (let i = 0; i < videos.length; i++) { setupVideo(videos[i]); } function setupVideo(video) { let link = video.querySelector('.news-post__full-video-link'); let media = video.querySelector('.news-post__full-video-media'); let button = video.querySelector('.news-post__full-video-button'); let id = parseMediaURL(media); video.addEventListener('click', () => { let iframe = createIframe(id); link.remove(); button.remove(); video.appendChild(iframe); link.removeAttribute('href'); video.classList.add('video--enabled'); videoControl(); }); } function parseMediaURL(media) { let regexp = /https:\/\/i\.ytimg\.com\/vi\/([a-zA-Z0-9_-]+)\/maxresdefault\.jpg/i; let url = media.src; let match = url.match(regexp); return match[1]; } function createIframe(id) { let iframe = document.createElement('iframe'); iframe.setAttribute('allowfullscreen', ''); iframe.setAttribute('allow', 'autoplay'); iframe.setAttribute('src', generateURL(id)); iframe.classList.add('video__media'); iframe.setAttribute("id", "newsVideo"); return iframe; } function generateURL(id) { let query = '?rel=0&showinfo=0&autoplay=1&enablejsapi=1'; return 'https://www.youtube.com/embed/' + id + query; } } } fullPostSliderVideoNews(); //Video in universal slider function fullPostSliderVideoNewsUniversal() { let videos = document.querySelectorAll('.news-post__full-video--universal'); if (videos === null) { // console.log("sliderVideos left HTML"); } else { for (let i = 0; i < videos.length; i++) { setupVideo(videos[i]); } function setupVideo(video) { let link = video.querySelector('.news-post__full-video-link'); let media = video.querySelector('.news-post__full-video-media'); let button = video.querySelector('.news-post__full-video-button'); let id = parseMediaURL(media); video.addEventListener('click', () => { let iframe = createIframe(id); link.remove(); button.remove(); video.appendChild(iframe); link.removeAttribute('href'); video.classList.add('video--enabled'); videoControl(); }); } function parseMediaURL(media) { let regexp = /https:\/\/i\.ytimg\.com\/vi\/([a-zA-Z0-9_-]+)\/maxresdefault\.jpg/i; let url = media.src; let match = url.match(regexp); return match[1]; } function createIframe(id) { let iframe = document.createElement('iframe'); iframe.setAttribute('allowfullscreen', ''); iframe.setAttribute('allow', 'autoplay'); iframe.setAttribute('src', generateURL(id)); iframe.classList.add('video__media'); iframe.setAttribute("id", "newsVideo"); return iframe; } function generateURL(id) { let query = '?rel=0&showinfo=0&autoplay=1&enablejsapi=1'; return 'https://www.youtube.com/embed/' + id + query; } } } //Video control function videoControl(){ // console.warn('videoCntrl function'); let iframes = document.querySelectorAll('iframe'); // console.log(iframes); let nextBtn = document.querySelectorAll('.news-post__full-slider-control-next'); let prevBtn = document.querySelectorAll('.news-post__full-slider-control-prev'); for(let i = 0; i < nextBtn.length; i++){ nextBtn[i].addEventListener('click', function(){ console.warn('BAM!!'); let pauseAllYouTubeVideos = () => { let iframes = document.querySelectorAll('iframe'); Array.prototype.forEach.call(iframes, iframe => { iframe.contentWindow.postMessage(JSON.stringify({ event: 'command', func: 'pauseVideo' }), '*'); }); } pauseAllYouTubeVideos(); }); } for(let i = 0; i < prevBtn.length; i++){ prevBtn[i].addEventListener('click', function(){ console.warn('BAM!!'); let pauseAllYouTubeVideos = () => { let iframes = document.querySelectorAll('iframe'); Array.prototype.forEach.call(iframes, iframe => { iframe.contentWindow.postMessage(JSON.stringify({ event: 'command', func: 'pauseVideo' }), '*'); }); } pauseAllYouTubeVideos(); }); } window.addEventListener('scroll', function(){ let pauseAllYouTubeVideos = () => { let iframes = document.querySelectorAll('iframe'); Array.prototype.forEach.call(iframes, iframe => { iframe.contentWindow.postMessage(JSON.stringify({ event: 'command', func: 'pauseVideo' }), '*'); }); } pauseAllYouTubeVideos(); }); } //height of video, if it`s alone in news-post__full-block-minimized-wrapper without slider function aloneVideoInNews(){ let videoBlocks = document.querySelectorAll('.news-post__full-video'); let intViewportWidth = window.innerWidth; if(videoBlocks === null){ // console.log('no video'); }else{ videoBlocks.forEach(item => { const videoParentElement = item.parentElement; if(videoParentElement.classList.contains('news-post__full-block-minimized-wrapper')){ if(intViewportWidth > 1140){ item.style.height = '650px'; }else if(intViewportWidth < 1140 && intViewportWidth >= 768){ item.style.height = '470px'; }else if(intViewportWidth < 768 && intViewportWidth > 475){ item.style.height = '400px'; }else if(intViewportWidth < 475){ item.style.height = '245px'; } } }); } } aloneVideoInNews() function showMoreBtnRotate() { const showMoreBtn = document.querySelector(".show-more"); const showMoreIconBtn = document.querySelector(".show-more__icon"); if (showMoreBtn === null || showMoreIconBtn === null ) { // console.log("showMoreButnRotate left html"); } else { showMoreBtn.addEventListener("mouseover", function() { showMoreIconBtn.classList.add("show-more__icon--rotate"); }); showMoreBtn.addEventListener("click", function() { showMoreIconBtn.classList.add("show-more__icon--click"); }); showMoreBtn.addEventListener("mouseout", function() { showMoreIconBtn.classList.remove("show-more__icon--rotate"); showMoreIconBtn.classList.remove("show-more__icon--click"); }); } } // showMoreBtnRotate(); //single news post mech function singleNewsPostMech(){ let singleNewsPostContainer = document.querySelector('.single-news-post'); if(singleNewsPostContainer === null){ // console.log('no single post on the page'); } else{ // console.warn('news post single'); let singleNewsPost = singleNewsPostContainer.querySelector('.news-post'); let singleNewsPostPanel = singleNewsPost.querySelector('.news-post__short-panel'); let singleNewsPostFull = singleNewsPost.querySelector('.news-post__full'); let singleNewsPostTitle = singleNewsPost.querySelector('.news-post__short-title'); let singleNewsPostClose = singleNewsPost.querySelector('.news-post__full-close'); singleNewsPostContainer.style.marginBottom = '35px'; if(singleNewsPostClose === null){ newPostSliderSingle(); fullPostSliderVideoNews(); }else{ singleNewsPostTitle.style.pointerEvents = 'none'; singleNewsPostPanel.style.display = 'none'; singleNewsPostFull.style.display = 'block'; singleNewsPostClose.style.display = 'none'; newPostSliderSingle(); fullPostSliderVideoNews(); } } } // Brand New Full post slider in opened card function newPostSliderSingleUniversal(){ let slider = document.querySelectorAll('.news-post__full-slider--universal'); if(slider === null){ // console.log('no news post slider on the page'); } else{ for(let i = 0; i < slider.length; i++){ let sliderItems = slider[i].querySelector('.news-post__full-slides'); let sliderSlide = slider[i].querySelectorAll('.news-post__full-slide'); let prev = slider[i].querySelector('.news-post__full-slider-control-prev'); let next = slider[i].querySelector('.news-post__full-slider-control-next'); let sliderWrapper = slider[i].querySelector('.news-post__full-slider-wrapper'); const sliderParent = slider[i].parentElement; const dataHeightDesktopOfSlider = sliderParent.dataset.heightDesktop; const dataHeightTabletOfSlider = sliderParent.dataset.heightTablet; const dataHeightMobileOfSlider = sliderParent.dataset.heightMobile; let parentOfSlider = slider[i].parentElement; //More space to full slider function newPostSliderSingleDynamicHeight(){ // console.warn('i`m here! newPostSliderSingleDynamicHeight '); let intViewportWidth = window.innerWidth; if(intViewportWidth < 499){ // console.warn('i`m here! newPostSliderSingle mobile size'); sliderWrapper.style.minHeight = dataHeightMobileOfSlider + "px"; slider[i].style.minHeight = dataHeightMobileOfSlider + "px"; sliderWrapper.style.maxHeight = dataHeightMobileOfSlider + "px"; slider[i].style.maxHeight = dataHeightMobileOfSlider + "px"; sliderParent.style.maxHeight = dataHeightMobileOfSlider + "px"; sliderParent.style.minHeight = dataHeightMobileOfSlider + "px"; sliderSlide.forEach(item => { item.style.minHeight = dataHeightMobileOfSlider + "px"; let slidePic = item.querySelector('img'); slidePic.style.height = dataHeightMobileOfSlider + "px"; }) }else if(intViewportWidth < 1140){ // console.warn('i`m here! newPostSliderSingle tablet size'); sliderWrapper.style.minHeight = dataHeightTabletOfSlider+ "px"; slider[i].style.minHeight = dataHeightTabletOfSlider+ "px"; sliderWrapper.style.maxHeight = dataHeightTabletOfSlider+ "px"; slider[i].style.maxHeight = dataHeightTabletOfSlider+ "px"; sliderParent.style.maxHeight = dataHeightTabletOfSlider + "px"; sliderParent.style.minHeight = dataHeightTabletOfSlider + "px"; sliderSlide.forEach(item => { item.style.minHeight = dataHeightTabletOfSlider+ "px"; let slidePic = item.querySelector('img'); slidePic.style.height = dataHeightTabletOfSlider+ "px"; }) }else{ // console.warn('i`m here! newPostSliderSingle Desktpop size'); sliderWrapper.style.minHeight = dataHeightDesktopOfSlider + "px"; slider[i].style.minHeight = dataHeightDesktopOfSlider + "px"; sliderWrapper.style.maxHeight = dataHeightDesktopOfSlider + "px"; slider[i].style.maxHeight = dataHeightDesktopOfSlider + "px"; sliderParent.style.maxHeight = dataHeightDesktopOfSlider + "px"; sliderParent.style.minHeight = dataHeightDesktopOfSlider + "px"; sliderSlide.forEach(item => { item.style.minHeight = dataHeightDesktopOfSlider + "px"; }) } } newPostSliderSingleDynamicHeight() //Check how many slides in slide if(sliderSlide.length === 1){ // console.warn('one slide! turn off slider'); prev.style.display = 'none'; next.style.display = 'none'; sliderSlide.forEach(item => { item.style.maxWidth = sliderWrapper.offsetWidth + "px"; }); }else{ sliderItems.style.left ='-' + sliderWrapper.offsetWidth + 'px'; console.warn('sliderWrapper.offsetWidth') console.warn(sliderWrapper.offsetWidth) sliderSlide.forEach(item => { item.style.width = sliderWrapper.offsetWidth + 'px'; item.style.height = sliderWrapper.offsetHight + 'px'; }) function slideSingle(wrapper, items, prev, next) { let posX1 = 0, posX2 = 0, posInitial, posFinal, threshold = 100, slides = items.getElementsByClassName('news-post__full-slide'), slidesLength = slides.length, slideSize = items.getElementsByClassName('news-post__full-slide')[0].offsetWidth, firstSlide = slides[0], lastSlide = slides[slidesLength - 1], cloneFirst = firstSlide.cloneNode(true), cloneLast = lastSlide.cloneNode(true), index = 0, allowShift = true; // Clone first and last slide items.appendChild(cloneFirst); items.insertBefore(cloneLast, firstSlide); wrapper.classList.add('loaded'); // Click events prev.addEventListener('click', function (e) { e.preventDefault(); shiftSlide(-1); }); next.addEventListener('click', function (e) { e.preventDefault(); shiftSlide(1); }); // Transition events items.addEventListener('transitionend', checkIndex); function shiftSlide(dir, action) { items.classList.add('shifting'); if (allowShift) { if (!action) { posInitial = items.offsetLeft; } if (dir == 1) { items.style.left = (posInitial - slideSize) + "px"; index++; } else if (dir == -1) { items.style.left = (posInitial + slideSize) + "px"; index--; } }; allowShift = false; } function checkIndex(){ items.classList.remove('shifting'); if (index == -1) { items.style.left = -(slidesLength * slideSize) + "px"; index = slidesLength - 1; } if (index == slidesLength) { items.style.left = -(1 * slideSize) + "px"; index = 0; } allowShift = true; } slider[i].classList.remove('news-post__full-slider--active'); } slideSingle(slider[i], sliderItems, prev, next); } } } } function singleUniversalSliderMech(){ let singleUniversalSliderContainer = document.querySelectorAll('.single-universal-slider'); if(singleUniversalSliderContainer === null){ // console.log('no single post on the page'); } else{ // console.warn('news post single'); newPostSliderSingleUniversal(); fullPostSliderVideoNewsUniversal(); } } singleUniversalSliderMech() function doubleNewsLinkToFullBar(){ let newsPost = document.querySelectorAll('.news-post') if(newsPost === null){ }else{ for (let i = 0; i < newsPost.length; i++) { const shortBtnAsk = newsPost[i].querySelector('.news-post__short-btn--ask'); const shortBtnShare = newsPost[i].querySelector('.news-post__short-btn--share'); const fullBtnAsk = newsPost[i].querySelector('.news-post__full-btn--ask'); const fullBtnShare = newsPost[i].querySelector('.news-post__full-btn--share'); if(shortBtnAsk){ fullBtnAsk.href = shortBtnAsk.href; } if(shortBtnShare){ fullBtnShare.href = shortBtnShare.href; } } } } doubleNewsLinkToFullBar(); function newsShareModal(){ let shareModal = document.querySelector('.modal-share'); let shareModalBlur = document.querySelector('.modal-share__blur'); let btnShareModalClose = document.querySelector('.modal-share__close'); let shareModalOpenBtn = document.querySelectorAll('.news-post__short-btn--share'); let shareModalFullOpenBtn = document.querySelectorAll('.news-post__full-btn--share'); let body = document.querySelector('body'); let modalUrl = document.querySelector('.modal-share__output'); let shareModalWrapper = document.querySelector('.modal-share__wrapper'); let newsPostTrigger = document.querySelector('.news-post'); if(newsPostTrigger){ function openShareModal(e) { e.preventDefault(); console.warn(this); console.log(modalUrl); modalUrl.innerHTML = this.href; shareModal.classList.add('modal-share--on'); body.classList.add('page-body__no-scroll'); shareModalWrapper.classList.add('modal-share__wrapper--opening'); } function closeShareModal() { shareModalWrapper.classList.remove('modal-share__wrapper--opening'); shareModalWrapper.classList.add('modal-share__wrapper--closing'); console.warn('newsShareModal action!') console.warn(shareModalOpenBtn) const handleAnimationEnd = function() { shareModal.classList.remove('modal-share--on'); shareModalWrapper.classList.remove('modal-share__wrapper--closing'); body.classList.remove('page-body__no-scroll'); shareModalWrapper.removeEventListener('animationend', handleAnimationEnd); }; shareModalWrapper.addEventListener('animationend', handleAnimationEnd); } if(shareModal === null || btnShareModalClose === null) { // console.warn('No modals here!'); } else { for(let i = 0; i < shareModalOpenBtn.length; i++){ shareModalOpenBtn[i].addEventListener('click', openShareModal); } for(let i = 0; i < shareModalFullOpenBtn.length; i++){ shareModalFullOpenBtn[i].addEventListener('click', openShareModal); } btnShareModalClose.addEventListener('click', closeShareModal); shareModalBlur.addEventListener('click', closeShareModal); } } } newsShareModal(); function newsAskModal() { let askModal = document.querySelector('.modal-ask'); let askModalBlur = document.querySelector('.modal-ask__blur'); let btnAskModalClose = document.querySelector('.modal-ask__close'); let askModalOpenBtn = document.querySelectorAll('.news-post__short-btn--ask'); let askModalFullOpenBtn = document.querySelectorAll('.news-post__full-btn--ask'); let askModalForm = document.querySelector('.modal-ask__form-inner'); let newsPostTrigger = document.querySelector('.news-post'); if(newsPostTrigger){ let url = document.querySelector("[name='SendQuestionForm[url]']"); let body = document.querySelector('body'); function openModal(e) { e.preventDefault(); askModal.classList.add('modal-ask--on'); body.classList.add('page-body__no-scroll'); url.value = this.href; askModalForm.classList.add('modal-ask__form-inner--opening'); // console.log(url); } function closeModal() { askModalForm.classList.remove('modal-ask__form-inner--opening'); askModalForm.classList.add('modal-ask__form-inner--closing'); console.warn('newsAskModal action!') const handleAnimationEnd = function() { askModal.classList.remove('modal-ask--on'); askModalForm.classList.remove('modal-ask__form-inner--closing'); body.classList.remove('page-body__no-scroll'); askModalForm.removeEventListener('animationend', handleAnimationEnd); }; askModalForm.addEventListener('animationend', handleAnimationEnd); } if(askModal && btnAskModalClose && askModalBlur) { askModalOpenBtn.forEach(btn => btn.addEventListener('click', openModal)); askModalFullOpenBtn.forEach(btn => btn.addEventListener('click', openModal)); btnAskModalClose.addEventListener('click', closeModal); askModalBlur.addEventListener('click', closeModal); } } } newsAskModal(); //Video in universal slider function fullPostSliderVideo() { let videos = document.querySelectorAll('.universal-slider__video'); if (videos === null) { // console.log("sliderVideos left HTML"); }else{ videos.forEach(video => { setupVideo(video) }); function setupVideo(video) { let link = video.querySelector('.universal-slider__video-link'); let media = video.querySelector('.universal-slider__video-media'); let button = video.querySelector('.universal-slider__video-button'); let id = parseMediaURL(media); video.addEventListener('click', () => { let iframe = createIframe(id); link.remove(); button.remove(); video.appendChild(iframe); link.removeAttribute('href'); video.classList.add('video--enabled'); videoControlForUniversalSlider(); }); } function parseMediaURL(media) { let regexp = /https:\/\/i\.ytimg\.com\/vi\/([a-zA-Z0-9_-]+)\/maxresdefault\.jpg/i; let url = media.src; let match = url.match(regexp); return match[1]; } function createIframe(id) { let iframe = document.createElement('iframe'); iframe.setAttribute('allowfullscreen', ''); iframe.setAttribute('allow', 'autoplay'); iframe.setAttribute('src', generateURL(id)); iframe.classList.add('video__media'); iframe.setAttribute("id", "newsVideo"); return iframe; } function generateURL(id) { let query = '?rel=0&showinfo=0&autoplay=1&enablejsapi=1'; return 'https://www.youtube.com/embed/' + id + query; } } } // fullPostSliderVideo(); //News Slider on mane page function newsSlider() { const modifiers = { controlNews: 'news-slider__control--active', }; const elNews = document.querySelector('.js-news-slider'); if (elNews === null) { // console.log("newsSlider left html"); } else { const newsItem = elNews.querySelectorAll('.js-news-slider__item'); const newsItems = elNews.querySelector('.js-news-slider__items'); const newsNext = elNews.querySelector('.js-news-slider__next'); const newsPrevious = elNews.querySelector('.js-news-slider__previous'); //Max value is scrollWidth - clientWidth, since it's the right side of the block const maxScrollValueN = newsItems.scrollWidth - elNews.clientWidth; //State values let currentSlideN = 0; let currentXN = 0; //Toggle controls visibility const updateNewsControls = () => { //Hide previous button if we are at the start newsPrevious.classList.toggle(modifiers.controlNews, currentXN !== 0); //Hide next button if we are at the end newsNext.classList.toggle(modifiers.controlNews, currentXN < maxScrollValueN); }; //Slide to card by its index const slideToNews = (index) => { //Check for minimal/maximal valid endexes if(index < 0 || index > newsItems.length - 1) return; //Get total width of all items. CSS is built the way that items don't have any offsets between them. //Padding are used for that reason let scrollValueN = 0; for(let i = 0; i < index; i++) { scrollValueN += newsItem[i].clientWidth; } //Limit by maximal scroll value const targetValueN = Math.min(scrollValueN, maxScrollValueN); //Scroll to card newsItems.scrollTo({left: targetValueN, behavior: 'smooth'}); //Update state values and controls currentSlideN = index; currentXN = targetValueN; updateNewsControls(); }; //Update controls on page load, They start hidden not to have visible controls that can't be clicked while js still loads. updateNewsControls(); //Whenever you click controls you go to next or previous index newsNext.addEventListener('click', () => slideToNews(currentSlideN + 1)); newsPrevious.addEventListener('click', () => slideToNews(currentSlideN - 1)); } } newsSlider();