fridge_bites/assets/js/single.js

112 lines
3.0 KiB
JavaScript

const recipeId = document.getElementById('recipe-id').textContent;
const toggleBtn = document.getElementById('day-select');
const dropdown = document.getElementById('custom-select-dropdown');
toggleBtn.addEventListener('click', () => {
dropdown.classList.toggle('hidden');
});
document.addEventListener('click', (e) => {
if (!dropdown.contains(e.target) && !toggleBtn.contains(e.target)) {
dropdown.classList.add('hidden');
}
});
const options = document.querySelectorAll('.dropdown-item');
options.forEach(option => {
option.addEventListener('click', () => {
const selectedValue = option.getAttribute('data-value');
options.forEach(opt => opt.classList.remove('dropdown-selected'));
if (selectedValue === 'remove') {
toggleBtn.textContent = 'Add to list';
} else {
toggleBtn.textContent = option.textContent;
option.classList.add('dropdown-selected');
}
dropdown.classList.add('hidden');
alert(`You selected: ${selectedValue}`);
});
});
const qrContainer = document.getElementById("qrcode");
const downloadLink = document.getElementById("downloadLink");
const qrBtn = document.getElementById("qr-btn");
const qrPopup = document.querySelector(".qr-popup");
const overlay = document.getElementById('overlay');
qrBtn.addEventListener("click", () => {
qrPopup.classList.toggle("hidden")
overlay.classList.toggle("hidden")
qrContainer.innerHTML = "";
new QRCode(qrContainer, {
text: window.location.href,
width: 200,
height: 200
});
setTimeout(() => {
const qrImg = qrContainer.querySelector("img");
if (qrImg) {
downloadLink.href = qrImg.src;
}
}, 500);
});
document.addEventListener('click', (e) =>{
if(!qrPopup.contains(e.target) && !qrBtn.contains(e.target)){
qrPopup.classList.add("hidden");
overlay.classList.add("hidden");
}
});
const favoriteBtn = document.getElementById('favorite-btn');
const favoriteIcon = favoriteBtn.querySelector('i');
favoriteBtn.addEventListener('click', async (e) => {
const isFavorite = favoriteBtn.classList.contains('active');
const type = isFavorite ? 'remove' : 'add';
const formData = new FormData();
formData.append('action', 'favorites');
formData.append('recipe_id', recipeId);
formData.append('type', type);
favoriteBtn.disabled = true;
const response = await fetch('/ajax', {
method: 'POST',
body: formData
});
favoriteBtn.disabled = false;
const json = await response.json();
if(!response.ok) {
const message = json.error;
showToastify(message, 'error');
return;
}
favoriteBtn.classList.toggle('active');
if(type == 'add') {
favoriteIcon.classList.remove('fa-regular');
favoriteIcon.classList.add('fa-solid');
} else {
favoriteIcon.classList.add('fa-regular');
favoriteIcon.classList.remove('fa-solid');
}
showToastify(json.success, 'success');
});