Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <script>
- // Configuración de moneda y formato
- const CURRENCY_CODE = 'MXN';
- const CURRENCY_SYMBOL = '$';
- const DECIMAL_PLACES = 2;
- const THOUSANDS_SEPARATOR = ',';
- const DECIMAL_SEPARATOR = '.';
- // Definición del producto
- const product = {
- name: "Nike Air Zoom TR 1",
- basePrice: 2999.00,
- attributes: [
- {
- name: "Color",
- options: [
- { name: "Negro", image: "https://ovdemos.s3-tastewp.com/wp-content/uploads/2024/10/tenis-nike_c-negro.jpg" },
- { name: "Azul", priceAdjustment: -50, image: "https://ovdemos.s3-tastewp.com/wp-content/uploads/2024/10/tenis-nike_c-azul.jpg" },
- { name: "Turquesa", priceAdjustment: 50, image: "https://ovdemos.s3-tastewp.com/wp-content/uploads/2024/10/tenis-nike_c-negro-turquesa.jpg" },
- { name: "Naranja", image: "https://ovdemos.s3-tastewp.com/wp-content/uploads/2024/10/tenis-nike_c-naranja.jpg" }
- ]
- },
- {
- name: "Talla",
- options: ["7", "7.5", "8", "8.5", "9", "9.5", "10"]
- }
- ],
- defaultImage: "https://ovdemos.s3-tastewp.com/wp-content/uploads/2024/10/tenis-nike_c-negro.jpg",
- thumbnails: [
- "https://ovdemos.s3-tastewp.com/wp-content/uploads/2024/10/tenis-nike_c-negro-turquesa.jpg",
- "https://ovdemos.s3-tastewp.com/wp-content/uploads/2024/10/tenis-nike_c-naranja.jpg",
- "https://ovdemos.s3-tastewp.com/wp-content/uploads/2024/10/tenis-nike_c-azul.jpg"
- ]
- };
- // Configuración de opciones de envío
- const shippingOptions = {
- Normal: {
- name: "Envío normal",
- price: 0,
- time: "5-8 días"
- },
- Express: {
- name: "Envío Express",
- price: 90,
- time: "1-3 días"
- }
- };
- // Variables globales
- let cart = [];
- // Funciones
- function formatPrice(amount) {
- if (typeof amount === 'number') {
- return CURRENCY_SYMBOL + amount.toFixed(DECIMAL_PLACES).replace(/\d(?=(\d{3})+\.)/g, '$&' + THOUSANDS_SEPARATOR).replace('.', DECIMAL_SEPARATOR) + ' ' + CURRENCY_CODE;
- } else if (typeof amount === 'string') {
- return CURRENCY_SYMBOL + parseFloat(amount).toFixed(DECIMAL_PLACES).replace(/\d(?=(\d{3})+\.)/g, '$&' + THOUSANDS_SEPARATOR).replace('.', DECIMAL_SEPARATOR) + ' ' + CURRENCY_CODE;
- } else {
- return CURRENCY_SYMBOL + '0.00' + ' ' + CURRENCY_CODE;
- }
- }
- function generateThumbnails() {
- const container = document.querySelector('.thumbnail-container');
- container.innerHTML = '';
- const attributeWithImages = product.attributes.find(attr =>
- attr.options.some(option => option.image)
- );
- if (attributeWithImages) {
- attributeWithImages.options.forEach((option, index) => {
- if (option.image) {
- const img = document.createElement('img');
- img.src = option.image;
- img.alt = `Vista ${option.name}`;
- img.className = 'thumbnail';
- img.dataset.attributeName = attributeWithImages.name;
- img.dataset.attributeValue = option.name;
- img.addEventListener('click', function() {
- updateMainImage(this);
- updateAttributeSelection(this.dataset.attributeName, this.dataset.attributeValue);
- });
- container.appendChild(img);
- }
- });
- } else {
- const defaultThumb = document.createElement('img');
- defaultThumb.src = product.defaultImage;
- defaultThumb.alt = "Vista principal";
- defaultThumb.className = 'thumbnail';
- defaultThumb.addEventListener('click', function() {
- updateMainImage(this);
- });
- container.appendChild(defaultThumb);
- }
- if (container.children.length === 0) {
- container.style.display = 'none';
- }
- }
- function generateAttributeSelectors() {
- const container = document.getElementById('product-attributes');
- container.innerHTML = '';
- product.attributes.forEach(attr => {
- const label = document.createElement('label');
- label.textContent = attr.name + ':';
- container.appendChild(label);
- const buttonContainer = document.createElement('div');
- buttonContainer.className = 'option-buttons';
- buttonContainer.id = `${attr.name.toLowerCase()}-options`;
- attr.options.forEach(option => {
- const button = document.createElement('button');
- button.type = 'button';
- button.className = 'option-button';
- if (typeof option === 'object') {
- button.dataset.value = option.name;
- button.dataset.priceAdjustment = option.priceAdjustment || 0;
- if (option.image) {
- button.dataset.image = option.image;
- }
- let priceText = option.name;
- if (option.priceAdjustment) {
- if (option.priceAdjustment > 0) {
- priceText += ` (+${formatPrice(option.priceAdjustment)})`;
- } else {
- priceText += ` (-${formatPrice(Math.abs(option.priceAdjustment))})`;
- }
- }
- button.textContent = priceText;
- } else {
- button.dataset.value = option;
- button.dataset.priceAdjustment = 0;
- button.textContent = option;
- }
- buttonContainer.appendChild(button);
- });
- container.appendChild(buttonContainer);
- });
- document.querySelectorAll('.option-button').forEach(button => {
- button.addEventListener('click', function() {
- selectOption(this);
- });
- });
- }
- function generateShippingOptions() {
- const select = document.querySelector('.shipping-options');
- select.innerHTML = '<option value="" disabled selected>Opciones de envío</option>';
- for (const [key, option] of Object.entries(shippingOptions)) {
- select.innerHTML += `<option value="${key}">${option.name} (${option.time}) - ${formatPrice(option.price)}</option>`;
- }
- }
- function updateMainImage(thumbnail) {
- document.getElementById('main-image').src = thumbnail.src;
- }
- function updateAttributeSelection(attributeName, value) {
- const attributeContainer = document.getElementById(`${attributeName.toLowerCase()}-options`);
- if (attributeContainer) {
- const button = attributeContainer.querySelector(`[data-value="${value}"]`);
- if (button) {
- selectOption(button, false);
- }
- }
- }
- function updatePrice() {
- let totalPrice = product.basePrice;
- product.attributes.forEach(attr => {
- const selected = document.querySelector(`#${attr.name.toLowerCase()}-options .selected`);
- if (selected) {
- totalPrice += parseFloat(selected.dataset.priceAdjustment);
- }
- });
- document.getElementById('product-price').textContent = formatPrice(totalPrice);
- }
- function selectOption(button, updateImage = true) {
- const attributeName = button.closest('.option-buttons').id.replace('-options', '');
- button.parentElement.querySelectorAll('.option-button').forEach(btn => {
- btn.classList.remove('selected');
- });
- button.classList.add('selected');
- if (updateImage && button.dataset.image) {
- updateMainImage({ src: button.dataset.image });
- const thumbnails = document.querySelectorAll('.thumbnail');
- thumbnails.forEach(thumb => {
- if (thumb.dataset.attributeName === attributeName &&
- thumb.dataset.attributeValue === button.dataset.value) {
- thumb.classList.add('selected');
- } else {
- thumb.classList.remove('selected');
- }
- });
- }
- updatePrice();
- }
- function updateCart() {
- const cartItems = document.getElementById('cart-items');
- const cartTotal = document.getElementById('cart-total');
- const checkoutButton = document.getElementById('checkout');
- const cartWarning = document.getElementById('cart-warning');
- let total = 0;
- cartItems.innerHTML = '';
- cart.forEach((item, index) => {
- const li = document.createElement('li');
- let itemDescription = `${item.name}`;
- for (const [attrName, attrValue] of Object.entries(item.attributes)) {
- itemDescription += ` - ${attrName}: ${attrValue}`;
- }
- li.innerHTML = `
- ${itemDescription} - ${formatPrice(item.price)}
- <button class="remove-item" data-index="${index}">M</button>
- `;
- cartItems.appendChild(li);
- total += item.price;
- });
- cartTotal.textContent = formatPrice(total);
- document.getElementById('whatsapp-total').textContent = formatPrice(total);
- if (cart.length > 0) {
- checkoutButton.disabled = false;
- cartWarning.style.display = 'none';
- } else {
- checkoutButton.disabled = true;
- cartWarning.style.display = 'block';
- }
- }
- function showPopup() {
- document.getElementById('popup').style.display = 'flex';
- const numProducts = cart.length;
- document.getElementById('popup-product-name').textContent = `${product.name} x ${numProducts} productos`;
- updatePopupTotal();
- document.getElementById('popup-image').src = product.defaultImage;
- }
- function updatePopupTotal() {
- const shippingSelect = document.querySelector('.shipping-options');
- const shippingCost = shippingOptions[shippingSelect.value]?.price || 0;
- const total = cart.reduce((sum, item) => sum + item.price, 0) + shippingCost;
- document.getElementById('popup-price').textContent = formatPrice(total);
- document.getElementById('whatsapp-total').textContent = formatPrice(total);
- }
- function closePopup() {
- document.getElementById('popup').style.display = 'none';
- }
- function clearCart() {
- cart = [];
- updateCart();
- }
- function validateSelection() {
- const warning = document.getElementById('attribute-warning');
- const selectedAttributes = {};
- let totalPrice = product.basePrice;
- const allSelected = product.attributes.every(attr => {
- const selected = document.querySelector(`#${attr.name.toLowerCase()}-options .selected`);
- if (selected) {
- selectedAttributes[attr.name] = selected.dataset.value;
- totalPrice += parseFloat(selected.dataset.priceAdjustment);
- return true;
- }
- return false;
- });
- if (!allSelected) {
- warning.style.display = 'block';
- return false;
- }
- warning.style.display = 'none';
- return { valid: true, attributes: selectedAttributes, price: totalPrice };
- }
- // Event Listeners
- document.addEventListener('DOMContentLoaded', function() {
- document.getElementById('product-name').textContent = product.name;
- document.getElementById('product-price').textContent = formatPrice(product.basePrice);
- document.getElementById('main-image').src = product.defaultImage;
- generateThumbnails();
- generateAttributeSelectors();
- generateShippingOptions();
- product.attributes.forEach(attr => {
- const firstOption = document.querySelector(`#${attr.name.toLowerCase()}-options .option-button`);
- if (firstOption) {
- selectOption(firstOption);
- }
- });
- });
- document.getElementById('add-to-cart').addEventListener('click', function() {
- const result = validateSelection();
- if (result.valid) {
- const item = {
- name: product.name,
- price: result.price,
- attributes: result.attributes
- };
- cart.push(item);
- updateCart();
- }
- });
- document.getElementById('checkout').addEventListener('click', function() {
- if (cart.length > 0) {
- showPopup();
- }
- });
- document.getElementById('close-popup').addEventListener('click', closePopup);
- document.getElementById('popup').addEventListener('click', function(e) {
- if (e.target === this) {
- closePopup();
- }
- });
- document.addEventListener('keydown', function(e) {
- if (e.key === 'Escape') {
- closePopup();
- }
- });
- document.getElementById('clear-cart').addEventListener('click', clearCart);
- document.getElementById('cart-items').addEventListener('click', function(e) {
- if (e.target.classList.contains('remove-item')) {
- const index = e.target.dataset.index;
- cart.splice(index, 1);
- updateCart();
- }
- });
- document.querySelector('.shipping-options').addEventListener('change', updatePopupTotal);
- document.getElementById('order-form').addEventListener('submit', function(e) {
- e.preventDefault();
- const formData = new FormData(this);
- let message = `Nuevo pedido de ${product.name}:\n\n`;
- const fieldNames = {
- nombres: "Nombre",
- apellidos: "Apellidos",
- calle_numero: "Calle y número",
- colonia: "Colonia",
- codigo_postal: "Código postal",
- localidad: "Ciudad",
- estado: "Estado",
- pais: "País",
- envio: "Método de envío",
- pago: "Método de pago"
- };
- for (let [key, value] of formData.entries()) {
- let fieldName = fieldNames[key] || key.charAt(0).toUpperCase() + key.slice(1);
- if (key === 'envio') {
- const shippingOption = shippingOptions[value];
- value = `${shippingOption.name} (${shippingOption.time}) - ${formatPrice(shippingOption.price)}`;
- }
- message += `${fieldName}: ${value}\n`;
- }
- message += `\nProductos:\n`;
- cart.forEach(item => {
- let itemDescription = `• ${item.name}`;
- for (const [attrName, attrValue] of Object.entries(item.attributes)) {
- itemDescription += ` - ${attrName}: ${attrValue}`;
- }
- itemDescription += ` - ${formatPrice(item.price)}`;
- message += itemDescription + '\n';
- });
- const shippingSelect = document.querySelector('.shipping-options');
- const shippingCost = shippingOptions[shippingSelect.value]?.price || 0;
- const subtotal = cart.reduce((total, item) => total + item.price, 0);
- const total = subtotal + shippingCost;
- message += `\nSubtotal: ${formatPrice(subtotal)}`;
- message += `\nCosto de envío: ${formatPrice(shippingCost)}`;
- message += `\nTotal: ${formatPrice(total)}`;
- const whatsappLink = `https://wa.me/529512345678?text=${encodeURIComponent(message)}`; // Reemplaza el número de WhatsApp
- window.open(whatsappLink, '_blank');
- });
- // Inicializar el carrito
- updateCart();
- // Mover el div 'popup' después de 'et-main-area'
- var popup = document.getElementById('popup');
- var mainArea = document.getElementById('et-main-area');
- mainArea.parentNode.insertBefore(popup, mainArea.nextSibling);
- </script>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement