/
lr-ru_gitVerse
/
front
Обзор
Документация
Войти
/
lr-ru_gitVerse
/
front
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
Аналитика
Безопасность
master
source/js/modules/offersCatalog.js
5 618 строк
280 KB
Artem Naumov
init
28 окт 2024, 01:39
28 окт 2024, 01:39
9aa6803
Код
Авторство
О чём код?
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();