I have the following code for the spec and quantity… · The Chat Archive
Explore I have the following code for the spec and quantity selection modal: <div… Save Share Download ▾ ReportI have the following code for the spec and quantity selection modal:
<label for="spec-modal-qty" class="spec-modal-mt-16">數量:</label>
<div class="spec-modal-quantity-input">
<button type="button" class="spec-modal-qty-btn spec-modal-qty-minus" aria-label="減少數量">−</button>
<input type="number" id="spec-modal-qty" name="qty" value="1" min="1" step="1" />
<button type="button" class="spec-modal-qty-btn spec-modal-qty-plus" aria-label="增加數量">+</button>
</div>
<!-- Price Info Section - added -->
<div id="spec-modal-discount-price-info" aria-live="polite" aria-atomic="true">
<div class="spec-modal-price-info-row">
<div class="spec-modal-unit-price-label">單價:</div>
<div class="spec-modal-unit-price-value" id="spec-modal-unit-price">HK$0.00</div>
</div>
<div class="spec-modal-price-info-row">
<div class="spec-modal-discount-percent-label">折扣:</div>
<div class="spec-modal-discount-percent-value" id="spec-modal-discount-percent">-0%</div>
</div>
<div class="spec-modal-price-info-row spec-modal-total-price-row">
<div class="spec-modal-total-price-label">合計:</div>
<div class="spec-modal-total-price-value" id="spec-modal-total-price">HK$0.00</div>
</div>
</div>
<div class="spec-modal-error" aria-live="polite" style="color:red; margin-top: 8px;"></div>
<button type="submit" class="spec-modal-btn spec-modal-btn-main spec-modal-mt-24" style="width:100%">確認加入購物車</button>
</form>
</main>
</div>
</div>
/* Modal overlay /
.spec-modal-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.6);
display: none; / initially hidden */
justify-content: center;
align-items: center;
z-index: 1050;
overflow: hidden;
animation: spec-modal-fadeIn 0.3s ease forwards;
}
/* Modal window */
.spec-modal-window {
background: #fff;
border-radius: 12px;
max-height: 90vh;
max-width: 480px;
width: 90%;
display: flex;
flex-direction: column;
opacity: 0;
transform: translateY(20px);
animation: spec-modal-slideFadeIn 0.3s forwards;
overflow: hidden;
box-shadow: 0 4px 12px rgba(0,0,0,0.15);
}
/* Modal header */
.spec-modal-header {
padding: 16px 24px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
align-items: center;
}
.spec-modal-header h2 {
margin: 0;
font-weight: 700;
font-size: 1.25rem;
}
.spec-modal-close {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
line-height: 1;
}
/* Modal content */
.spec-modal-content {
padding: 24px;
overflow-y: auto;
flex-grow: 1;
}
/* Quantity input styles */
.spec-modal-quantity-input {
display: flex;
align-items: center;
max-width: 180px;
margin-top: 8px;
}
.spec-modal-qty-btn {
background-color: #e2e8f0;
border: none;
width: 36px;
height: 36px;
font-size: 1.5rem;
cursor: pointer;
border-radius: 50%;
line-height: 1;
user-select: none;
}
Assistant2025-06-29 09:37 UTC Copy response
Assistant2025-06-29 09:46 UTC Copy response
product can be without any spec selection, but current version display are not consider this type of product, so the price info are not updated when the quantity changed, please fix it
Assistant2025-06-29 10:16 UTC Copy response
Assistant2025-06-29 10:17 UTC Copy response
Assistant2025-06-29 11:05 UTC Copy response
Copy first prompt
Details
Provider OpenAI
Model provenance As recorded by source dataset
Turns 5 (10 messages)
Language en
Conversation date Jun 29, 2025
Added to archive Nov 17, 2026
ID 01m7h42wp5ycnhxy4k69eezkyvSource & license Imported from WildChat-4.8M (AI2) (source ). Imported records earn no Research Points.
Upstream record: 339fa61abae580a12c011220bdb9035d
Zhao et al., WildChat: 1M ChatGPT Interaction Logs in the Wild (ICLR 2024). Contains information from WildChat-4.8M, made available under the ODC Attribution License.
License: ODC-BY-1.0
.spec-modal-qty-btn:hover {
background-color: #cbd5e1;
}
#spec-modal-qty {
width: 64px;
height: 36px;
text-align: center;
font-size: 1rem;
border: 1px solid #ccc;
margin: 0 8px;
border-radius: 6px;
}
#spec-modal-variants-container {
margin-bottom: 18px;
}
/* Variant option styles */
.spec-modal-variant-group {
margin-bottom: 12px;
}
.spec-modal-variant-label {
display: block;
font-weight: 600;
margin-bottom: 4px;
}
.spec-modal-variant-options {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.spec-modal-variant-option {
border: 1px solid #b0bec5;
border-radius: 8px;
padding: 6px 10px;
cursor: pointer;
user-select: none;
font-size: 0.875rem;
background-color: #f8fafc;
transition: background-color 0.15s ease, border-color 0.15s ease;
}
.spec-modal-variant-option.selected,
.spec-modal-variant-option:hover {
border-color: #3b82f6;
background-color: #dbeafe;
}
.spec-modal-variant-option input[type="radio"] {
display: none;
}
/* Modal error */
.spec-modal-error {
color: red;
margin-top: 8px;
min-height: 1.5em;
}
/* Price Info Section */
#spec-modal-discount-price-info {
border-top: 1px solid #e0e0e0;
padding-top: 12px;
font-size: 1rem;
color: #333;
margin-top: 16px;
margin-bottom: 16px;
}
.spec-modal-price-info-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 6px;
}
.spec-modal-unit-price-value {
color: #e74c3c;
font-weight: 700;
}
.spec-modal-discount-percent-value {
background-color: #e67e22;
color: white;
padding: 2px 8px;
border-radius: 12px;
font-weight: 700;
font-size: 0.9rem;
white-space: nowrap;
}
.spec-modal-total-price-row {
margin-top: 8px;
font-weight: 700;
font-size: 1.1rem;
color: #222;
border-top: 1px solid #e0e0e0;
padding-top: 8px;
}
/* Utility */
.spec-modal-mt-16 {
margin-top: 16px;
}
.spec-modal-mt-24 {
margin-top: 24px;
}
.spec-modal-btn {
padding: 12px 24px;
border: none;
cursor: pointer;
border-radius: 6px;
font-weight: 600;
font-size: 1rem;
}
.spec-modal-btn-main {
background-color: #3b82f6;
color: white;
}
.spec-modal-btn-main:hover {
background-color: #2563eb;
}
/* Responsive styling */
@media (max-width: 767.98px) {
.spec-modal-overlay {
align-items: flex-end;
padding: 8px;
}
.spec-modal-window {
width: 100%;
max-width: unset;
border-radius: 16px 16px 0 0;
max-height: 70vh;
transform: translateY(100%);
animation: spec-modal-slideUpIn 0.3s forwards;
}
#spec-modal-discount-price-info {
font-size: 0.95rem;
}
.spec-modal-price-info-row {
margin-bottom: 4px;
}
}
@media (max-width: 479.98px) {
#spec-modal-discount-price-info {
font-size: 0.9rem;
}
.spec-modal-price-info-row {
flex-direction: column;
align-items: flex-start;
gap: 2px;
}
.spec-modal-price-info-row > div:last-child {
align-self: flex-end;
}
.spec-modal-total-price-row {
font-size: 1rem;
}
}
/* Animation keyframes */
@keyframes spec-modal-fadeIn {
to {opacity: 1;}
}
@keyframes spec-modal-slideFadeIn {
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes spec-modal-slideUpIn {
to {
opacity: 1;
transform: translateY(0);
}
}
(document).ready(function () {
const modal = ('#spec-modal-product-spec-modal');
const variantsContainer = modal.find('#spec-modal-variants-container');
const qtyInput = modal.find('#spec-modal-qty');
const qtyMinusBtn = modal.find('.spec-modal-qty-minus');
const qtyPlusBtn = modal.find('.spec-modal-qty-plus');
const modalCloseBtn = modal.find('.spec-modal-close');
const modalForm = modal.find('#spec-modal-product-spec-form');
const modalError = modal.find('.spec-modal-error');
let currentProductData = null;
let activeAddToCartBtn = null; // store clicked button to restore UI
function buildVariantOptions(variants) {
if (!Array.isArray(variants) || variants.length === 0) {
variantsContainer.html('');
return;
}
// Trim and split attr_name
const attrNames = variants[0].attr_name ? variants[0].attr_name.split(',').map(s => s.trim()) : [];
if (attrNames.length === 0) {
variantsContainer.html('');
return;
}
let attrValuesByName = {};
attrNames.forEach(attr => attrValuesByName[attr] = new Set());
variants.forEach(variant => {
if (!variant.variant_values) return;
const vals = variant.variant_values.split(',').map(s => s.trim());
vals.forEach((val, i) => {
if (attrNames[i]) attrValuesByName[attrNames[i]].add(val);
});
});
if (Object.values(attrValuesByName).every(set => set.size === 0)) {
variantsContainer.html('');
return;
}
let html = '';
attrNames.forEach((attrName, groupIndex) => {
html += `<div class="spec-modal-variant-group" data-variant-attribute="${attrName}">
<label class="spec-modal-variant-label">${attrName}:</label>
<div class="spec-modal-variant-options" role="radiogroup" aria-label="${attrName} options">`;
Array.from(attrValuesByName[attrName]).forEach((val, optionIndex) => {
const optionId = `spec-modal-variant-${attrName}-${optionIndex}`;
html += `
<label class="spec-modal-variant-option" for="${optionId}" tabindex="0" role="radio" aria-checked="false" data-variant-attr="${attrName}" data-variant-val="${val}">
<input type="radio" name="spec-modal-variant-${attrName}" id="${optionId}" value="${val}">
${val}
</label>`;
});
html += '</div></div>';
});
variantsContainer.html(html);
function updateSelectedStyles() {
variantsContainer.find('.spec-modal-variant-option').each(function () {
var label = $(this);
var input = label.find('input[type="radio"]');
if (input.prop('checked')) {
label.addClass('selected').attr('aria-checked', 'true');
} else {
label.removeClass('selected').attr('aria-checked', 'false');
}
});
}
updateSelectedStyles();
variantsContainer.find('.spec-modal-variant-option').on('click', function () {
var input = $(this).find('input[type="radio"]');
input.prop('checked', true).trigger('change');
updateSelectedStyles();
updatePriceInfo();
}).on('keydown', function (e) {
if (e.key === ' ' || e.key === 'Enter') {
e.preventDefault();
$(this).trigger('click');
}
});
variantsContainer.find('input[type="radio"]').on('change', function(){
updateSelectedStyles();
updatePriceInfo();
});
function updatePriceInfo() {
if (!currentProductData) return;
// Find selected attributes
let selectedAttributes = {};
let allSelected = true;
variantsContainer.find('.spec-modal-variant-group').each(function () {
const attrName = $(this).data('variant-attribute');
const checkedInput = $(this).find('input[type=radio]:checked');
if (checkedInput.length === 0) {
allSelected = false;
return false;
}
selectedAttributes[attrName] = checkedInput.val();
});
const unitPriceEl = $('#spec-modal-unit-price');
const discountPercentEl = $('#spec-modal-discount-percent');
const totalPriceEl = $('#spec-modal-total-price');
const qty = parseInt(qtyInput.val()) || 1;
if (!allSelected) {
unitPriceEl.text('—');
discountPercentEl.text('—');
totalPriceEl.text('—');
return;
}
// Find matched variant
let matchedVariant = currentProductData.variants.find(variant => {
if (!variant.attr_name || !variant.variant_values) return false;
const attrNames = variant.attr_name.split(',').map(s => s.trim());
const attrValues = variant.variant_values.split(',').map(s => s.trim());
for (let i = 0; i < attrNames.length; i++) {
if (selectedAttributes[attrNames[i]] !== attrValues[i]) return false;
}
return true;
});
if (!matchedVariant) {
unitPriceEl.text('—');
discountPercentEl.text('—');
totalPriceEl.text('—');
return;
}
const originalPrice = Number(matchedVariant.price) || 0;
const specialPrice = Number(matchedVariant.special_price) || originalPrice;
const discountPercent = originalPrice > 0 && specialPrice < originalPrice
? Math.round((1 - specialPrice / originalPrice) * 100)
: 0;
const totalPrice = specialPrice * qty;
function formatHKD(price) {
return 'HK$' + price.toFixed(2);
}
unitPriceEl.text(formatHKD(specialPrice));
discountPercentEl.text(discountPercent > 0 ? `-${discountPercent}%` : '無折扣');
totalPriceEl.text(formatHKD(totalPrice));
function openModal(productData, clickedBtn) {
currentProductData = productData;
activeAddToCartBtn = clickedBtn;
if (productData.hasMultipleVariants) {
buildVariantOptions(productData.variants);
variantsContainer.show();
} else {
variantsContainer.hide().html('');
}
const min = Number(productData.min) || 1;
const step = Number(productData.step) || 1;
const max = Number(productData.max) || null;
qtyInput.attr('min', min);
qtyInput.attr('step', step);
qtyInput.val(min);
if (max) {
qtyInput.attr('max', max);
} else {
qtyInput.removeAttr('max');
}
modalError.text('');
modal.fadeIn(200);
$('body').css('overflow', 'hidden');
updatePriceInfo();
function closeModal() {
modal.fadeOut(200);
$('body').css('overflow', '');
currentProductData = null;
activeAddToCartBtn = null;
variantsContainer.html('');
modalError.text('');
$('#spec-modal-unit-price').text('HK$0.00');
$('#spec-modal-discount-percent').text('-0%');
$('#spec-modal-total-price').text('HK$0.00');
// Quantity buttons logic
qtyMinusBtn.on('click', function () {
let val = parseInt(qtyInput.val()) || 1;
const min = parseInt(qtyInput.attr('min')) || 1;
const step = parseInt(qtyInput.attr('step')) || 1;
val = Math.max(min, val - step);
qtyInput.val(val);
updatePriceInfo();
});
qtyPlusBtn.on('click', function () {
let val = parseInt(qtyInput.val()) || 1;
const step = parseInt(qtyInput.attr('step')) || 1;
const max = parseInt(qtyInput.attr('max'));
val = val + step;
if (!isNaN(max)) val = Math.min(max, val);
qtyInput.val(val);
updatePriceInfo();
});
qtyInput.on('input change', function () {
let val = +qtyInput.val();
const min = +qtyInput.attr('min');
const max = +qtyInput.attr('max');
const step = +qtyInput.attr('step');
if (isNaN(val) || val < min) val = min;
if (!isNaN(max) && val > max) val = max;
if (step > 1) val = Math.round(val / step) * step;
qtyInput.val(val);
updatePriceInfo();
});
modalCloseBtn.on('click', closeModal);
modal.on('click', function (e) {
if (e.target === this) closeModal();
});
modalForm.on('submit', function (e) {
e.preventDefault();
modalError.text('');
if (!currentProductData) {
modalError.text('產品資料缺失');
return;
}
let selectedAttributes = {};
let valid = true;
variantsContainer.find('.spec-modal-variant-group').each(function () {
const attrName = $(this).data('variant-attribute');
const checkedInput = $(this).find('input[type=radio]:checked');
if (checkedInput.length === 0) {
modalError.text(`請選擇${attrName}`);
valid = false;
return false;
}
selectedAttributes[attrName] = checkedInput.val();
});
if (!valid) return;
let qty = parseInt(qtyInput.val());
const minQty = Number(currentProductData.min) || 1;
const maxQty = Number(currentProductData.max);
if (isNaN(qty) || qty < minQty) {
modalError.text(`數量不能小於 ${minQty}`);
return;
}
if (!isNaN(maxQty) && maxQty > 0 && qty > maxQty) {
modalError.text(`數量不能超過最大限制 ${maxQty}`);
return;
}
let matchedVariant = null;
if (currentProductData.hasMultipleVariants) {
matchedVariant = currentProductData.variants.find(variant => {
if (!variant.attr_name || !variant.variant_values) return false;
const attrNames = variant.attr_name.split(',').map(s => s.trim());
const attrValues = variant.variant_values.split(',').map(s => s.trim());
for (let i = 0; i < attrNames.length; i++) {
if (selectedAttributes[attrNames[i]] !== attrValues[i]) return false;
}
return true;
});
} else {
matchedVariant = currentProductData.variants && currentProductData.variants.length > 0
? currentProductData.variants[0]
: null;
}
if (!matchedVariant) {
modalError.text('請選擇有效的產品規格');
return;
}
closeModal();
// Your AJAX add to cart logic here (update base_url, csrfName, csrfHash, is_loggedin accordingly)
if (!matchedVariant.id) {
Swal.fire({
icon: 'error',
title: '錯誤',
text: '無法找到匹配的產品規格,請重試',
});
return;
}
$.ajax({
type: 'POST',
url: base_url + 'cart/manage',
data: {
product_variant_id: matchedVariant.id,
qty: qty,
is_saved_for_later: false,
[csrfName]: csrfHash,
},
dataType: 'json',
success: function (result) {
csrfName = result.csrfName;
csrfHash = result.csrfHash;
if (!result.error) {
Toast.fire({
icon: 'success',
title: result.message
});
$('.cart_count').each(function () {
$(this).text(result.data.cart_count);
});
display_cart(result.data.items);
} else {
if (is_loggedin == 0) {
Toast.fire({
icon: 'success',
title: "已加入至購物車"
});
var cart_item = {
product_variant_id: matchedVariant.id,
name: currentProductData.title || '',
short_description: currentProductData.description || '',
qty: qty,
image: currentProductData.image || '',
price: currentProductData.price
};
var cart = localStorage.getItem("cart");
cart = cart ? JSON.parse(cart) : [];
cart.push(cart_item);
localStorage.setItem("cart", JSON.stringify(cart));
display_cart(cart);
} else {
Toast.fire({
icon: 'error',
title: result.message
});
}
}
},
error: function () {
Toast.fire({
icon: 'error',
title: '伺服器錯誤,請稍後重試'
});
}
});
// Bind popup open on all add_to_cart buttons
(document).on('click', '.add_to_cart', function (e) {
e.preventDefault();
const btn = (this);
// Parse variants JSON from data attribute
let variantsData = [];
try {
variantsData = btn.attr('data-variants') ? JSON.parse(btn.attr('data-variants')) : [];
} catch {
variantsData = [];
}
const productData = {
id: btn.data('product-id'),
title: btn.data('product-title'),
name: btn.data('product-title'),
price: btn.data('product-price'),
image: btn.data('product-image'),
min: Number(btn.data('min')) || 1,
step: Number(btn.data('step')) || 1,
max: Number(btn.data('max')) || null,
variants: variantsData,
description: btn.data('product-description') || '',
hasMultipleVariants: btn.data('has-multiple-variants') === 1 || btn.data('has-multiple-variants') === '1',
};
openModal(productData, btn);
I want to modify the css to make the modal content show at center of screen in pc, tablet and mobile.
also, please make the part "spec-modal-discount-price-info" hidden by default until the user selected all required spec and quantity.
To achieve your requirements:
Center the modal content vertically and horizontally on all screen sizes (PC, tablet, and mobile).
Hide #spec-modal-discount-price-info by default and only show it after all specs and quantity have been selected.
1. Centering Modal Content on All Devices
Currently, your modal overlay .spec-modal-overlay uses display: none initially and then uses flex with justify-content: center; align-items: center;. This works for desktop but on mobile, you override the alignment to align-items: flex-end; which moves the modal to the bottom.
We want to center vertically and horizontally on all screen sizes.
Action: Remove the override at mobile media queries and adjust animation if needed.
2. Hiding .spec-modal-discount-price-info initially
Add CSS to hide it by default (e.g., display: none;), and then in your JS code, show it only when all variant specs and quantity are selected correctly.
Updated CSS
/* Modal overlay */
.spec-modal-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.6);
display: none; /* initially hidden */
justify-content: center;
align-items: center; /* Center vertically and horizontally */
z-index: 1050;
overflow: hidden;
animation: spec-modal-fadeIn 0.3s ease forwards;
}
/* Responsive styling */
@media (max-width: 767.98px) {
.spec-modal-overlay {
/* Remove align-items: flex-end to keep vertical centering */
/* align-items: flex-end; */
padding: 8px;
}
.spec-modal-window {
width: 100%;
max-width: unset;
border-radius: 16px 16px 0 0;
max-height: 70vh;
/* Remove translateY(100%) animation to keep it centered */
transform: translateY(20px);
animation: spec-modal-slideFadeIn 0.3s forwards; /* reuse desktop animation */
}
#spec-modal-discount-price-info {
font-size: 0.95rem;
}
.spec-modal-price-info-row {
margin-bottom: 4px;
}
}
@media (max-width: 479.98px) {
#spec-modal-discount-price-info {
font-size: 0.9rem;
}
.spec-modal-price-info-row {
flex-direction: column;
align-items: flex-start;
gap: 2px;
}
.spec-modal-price-info-row > div:last-child {
align-self: flex-end;
}
.spec-modal-total-price-row {
font-size: 1rem;
}
}
/* Hide discount-price-info by default */
#spec-modal-discount-price-info {
display: none;
}
JS Modification to Show Price Info Only After Complete Selection
Your existing updatePriceInfo function is called when variants or quantity changes. Currently, prices are displayed or replaced with '—' if not all specs are selected.
Modify it so the entire #spec-modal-discount-price-info container is only shown when all variants + quantity are valid and ready.
Add this snippet inside the end of updatePriceInfo():
function updatePriceInfo() {
if (!currentProductData) return;
// Find selected attributes
let selectedAttributes = {};
let allSelected = true;
variantsContainer.find('.spec-modal-variant-group').each(function () {
const attrName = $(this).data('variant-attribute');
const checkedInput = $(this).find('input[type=radio]:checked');
if (checkedInput.length === 0) {
allSelected = false;
return false;
}
selectedAttributes[attrName] = checkedInput.val();
});
const qty = parseInt(qtyInput.val()) || 1;
// Also check quantity is valid and >= min
const minQty = Number(currentProductData.min) || 1;
const maxQty = Number(currentProductData.max) || Infinity;
const isQtyValid = qty >= minQty && qty <= maxQty;
const discountPriceInfoEl = $('#spec-modal-discount-price-info');
if (!allSelected || !isQtyValid) {
// Hide price info section if incomplete
discountPriceInfoEl.hide();
return;
}
discountPriceInfoEl.show();
// Find matched variant
let matchedVariant = currentProductData.variants.find(variant => {
if (!variant.attr_name || !variant.variant_values) return false;
const attrNames = variant.attr_name.split(',').map(s => s.trim());
const attrValues = variant.variant_values.split(',').map(s => s.trim());
for (let i = 0; i < attrNames.length; i++) {
if (selectedAttributes[attrNames[i]] !== attrValues[i]) return false;
}
return true;
});
const unitPriceEl = $('#spec-modal-unit-price');
const discountPercentEl = $('#spec-modal-discount-percent');
const totalPriceEl = $('#spec-modal-total-price');
if (!matchedVariant) {
unitPriceEl.text('—');
discountPercentEl.text('—');
totalPriceEl.text('—');
return;
}
const originalPrice = Number(matchedVariant.price) || 0;
const specialPrice = Number(matchedVariant.special_price) || originalPrice;
const discountPercent = originalPrice > 0 && specialPrice < originalPrice
? Math.round((1 - specialPrice / originalPrice) * 100)
: 0;
const totalPrice = specialPrice * qty;
function formatHKD(price) {
return 'HK$' + price.toFixed(2);
}
unitPriceEl.text(formatHKD(specialPrice));
discountPercentEl.text(discountPercent > 0 ? `-${discountPercent}%` : '無折扣');
totalPriceEl.text(formatHKD(totalPrice));
}
Explanation:
This combined CSS and JS tweak will :
If you want me to provide the full updated code snippet with these integrated, just ask!
Please update the following css class and id with prefix spec-modal-
.modal-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.6);
display: flex;
justify-content: center;
align-items: center;
z-index: 1050;
overflow: hidden;
animation: fadeIn 0.3s ease forwards;
}
.modal-window {
background: #fff;
border-radius: 12px;
max-height: 90vh;
max-width: 480px;
width: 90%;
display: flex;
flex-direction: column;
opacity: 0;
transform: translateY(20px);
animation: slideFadeIn 0.3s forwards;
overflow: hidden;
}
.modal-header {
padding: 16px 24px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
align-items: center;
}
.modal-header h2 {
margin: 0;
font-weight: 700;
font-size: 1.25rem;
}
.modal-close {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
line-height: 1;
}
.modal-content {
padding: 24px;
overflow-y: auto;
flex-grow: 1;
}
.quantity-input {
display: flex;
align-items: center;
max-width: 180px;
margin-top: 8px;
}
.qty-btn {
background-color: #e2e8f0;
border: none;
width: 36px;
height: 36px;
font-size: 1.5rem;
cursor: pointer;
border-radius: 50%;
line-height: 1;
user-select: none;
}
.qty-btn:hover {
background-color: #cbd5e1;
}
#modal-qty {
width: 64px;
height: 36px;
text-align: center;
font-size: 1rem;
border: 1px solid #ccc;
margin: 0 8px;
border-radius: 6px;
}
#variants-container {
margin-bottom: 18px;
}
/* Variant option styles */
.variant-group {
margin-bottom: 12px;
}
.variant-label {
display: block;
font-weight: 600;
margin-bottom: 4px;
}
.variant-options {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.variant-option {
border: 1px solid #b0bec5;
border-radius: 8px;
padding: 6px 10px;
cursor: pointer;
user-select: none;
font-size: 0.875rem;
background-color: #f8fafc;
transition: background-color 0.15s ease, border-color 0.15s ease;
}
.variant-option.selected,
.variant-option:hover {
border-color: #3b82f6;
background-color: #dbeafe;
}
.variant-option input[type="radio"] {
display: none;
}
@media (max-width: 767.98px) {
.modal-overlay {
align-items: flex-end;
padding: 8px;
}
.modal-window {
width: 100%;
max-width: unset;
border-radius: 16px 16px 0 0;
max-height: 70vh;
transform: translateY(100%);
animation: slideUpIn 0.3s forwards;
}
}
@keyframes fadeIn {
to {opacity: 1;}
}
@keyframes slideFadeIn {
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes slideUpIn {
to {
opacity: 1;
transform: translateY(0);
}
}
#discount-price-info {
border-top: 1px solid #e0e0e0;
padding-top: 12px;
font-size: 1rem;
color: #333;
}
.price-info-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 6px;
}
.unit-price-value {
color: #e74c3c;
font-weight: 700;
}
.discount-percent-value {
background-color: #e67e22;
color: white;
padding: 2px 8px;
border-radius: 12px;
font-weight: 700;
font-size: 0.9rem;
white-space: nowrap;
}
.total-price-row {
margin-top: 8px;
font-weight: 700;
font-size: 1.1rem;
color: #222;
border-top: 1px solid #e0e0e0;
padding-top: 8px;
}
@media (max-width: 767.98px) {
#discount-price-info {
font-size: 0.95rem;
}
.price-info-row {
margin-bottom: 4px;
}
}
@media (max-width: 479.98px) {
#discount-price-info {
font-size: 0.9rem;
}
.price-info-row {
flex-direction: column;
align-items: flex-start;
gap: 2px;
}
.price-info-row > div:last-child {
align-self: flex-end;
}
.total-price-row {
font-size: 1rem;
}
}
Certainly! Here's the updated CSS with all class names and IDs prefixed by spec-modal- as requested:
.spec-modal-overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,0.6);
display: flex;
justify-content: center;
align-items: center;
z-index: 1050;
overflow: hidden;
animation: spec-modal-fadeIn 0.3s ease forwards;
}
.spec-modal-window {
background: #fff;
border-radius: 12px;
max-height: 90vh;
max-width: 480px;
width: 90%;
display: flex;
flex-direction: column;
opacity: 0;
transform: translateY(20px);
animation: spec-modal-slideFadeIn 0.3s forwards;
overflow: hidden;
}
.spec-modal-header {
padding: 16px 24px;
border-bottom: 1px solid #eee;
display: flex;
justify-content: space-between;
align-items: center;
}
.spec-modal-header h2 {
margin: 0;
font-weight: 700;
font-size: 1.25rem;
}
.spec-modal-close {
background: none;
border: none;
font-size: 1.5rem;
cursor: pointer;
line-height: 1;
}
.spec-modal-content {
padding: 24px;
overflow-y: auto;
flex-grow: 1;
}
.spec-modal-quantity-input {
display: flex;
align-items: center;
max-width: 180px;
margin-top: 8px;
}
.spec-modal-qty-btn {
background-color: #e2e8f0;
border: none;
width: 36px;
height: 36px;
font-size: 1.5rem;
cursor: pointer;
border-radius: 50%;
line-height: 1;
user-select: none;
}
.spec-modal-qty-btn:hover {
background-color: #cbd5e1;
}
#spec-modal-qty {
width: 64px;
height: 36px;
text-align: center;
font-size: 1rem;
border: 1px solid #ccc;
margin: 0 8px;
border-radius: 6px;
}
#spec-modal-variants-container {
margin-bottom: 18px;
}
/* Variant option styles */
.spec-modal-variant-group {
margin-bottom: 12px;
}
.spec-modal-variant-label {
display: block;
font-weight: 600;
margin-bottom: 4px;
}
.spec-modal-variant-options {
display: flex;
gap: 12px;
flex-wrap: wrap;
}
.spec-modal-variant-option {
border: 1px solid #b0bec5;
border-radius: 8px;
padding: 6px 10px;
cursor: pointer;
user-select: none;
font-size: 0.875rem;
background-color: #f8fafc;
transition: background-color 0.15s ease, border-color 0.15s ease;
}
.spec-modal-variant-option.selected,
.spec-modal-variant-option:hover {
border-color: #3b82f6;
background-color: #dbeafe;
}
.spec-modal-variant-option input[type="radio"] {
display: none;
}
@media (max-width: 767.98px) {
.spec-modal-overlay {
align-items: flex-end;
padding: 8px;
}
.spec-modal-window {
width: 100%;
max-width: unset;
border-radius: 16px 16px 0 0;
max-height: 70vh;
transform: translateY(100%);
animation: spec-modal-slideUpIn 0.3s forwards;
}
}
@keyframes spec-modal-fadeIn {
to {opacity: 1;}
}
@keyframes spec-modal-slideFadeIn {
to {
opacity: 1;
transform: translateY(0);
}
}
@keyframes spec-modal-slideUpIn {
to {
opacity: 1;
transform: translateY(0);
}
}
#spec-modal-discount-price-info {
border-top: 1px solid #e0e0e0;
padding-top: 12px;
font-size: 1rem;
color: #333;
}
.spec-modal-price-info-row {
display: flex;
justify-content: space-between;
align-items: center;
margin-bottom: 6px;
}
.spec-modal-unit-price-value {
color: #e74c3c;
font-weight: 700;
}
.spec-modal-discount-percent-value {
background-color: #e67e22;
color: white;
padding: 2px 8px;
border-radius: 12px;
font-weight: 700;
font-size: 0.9rem;
white-space: nowrap;
}
.spec-modal-total-price-row {
margin-top: 8px;
font-weight: 700;
font-size: 1.1rem;
color: #222;
border-top: 1px solid #e0e0e0;
padding-top: 8px;
}
@media (max-width: 767.98px) {
#spec-modal-discount-price-info {
font-size: 0.95rem;
}
.spec-modal-price-info-row {
margin-bottom: 4px;
}
}
@media (max-width: 479.98px) {
#spec-modal-discount-price-info {
font-size: 0.9rem;
}
.spec-modal-price-info-row {
flex-direction: column;
align-items: flex-start;
gap: 2px;
}
.spec-modal-price-info-row > div:last-child {
align-self: flex-end;
}
.spec-modal-total-price-row {
font-size: 1rem;
}
}
All class selectors and IDs now start consistently with spec-modal-.
Let me know if you want me to also update the keyframe names or any other part!
Got it! For products without any specs (i.e., products with no variants, or only one variant without attributes), your current code skips updating the price info when changing quantity.
What’s happening now?
When currentProductData.hasMultipleVariants is false, variantsContainer is hidden and empty.
The updatePriceInfo expects variants and selected specs to calculate price.
So when no specs are required, no update happens on quantity changes.
Solution
We need to update the updatePriceInfo() function to correctly handle:
Products without multiple variants , i.e. no specs needed.
In that case, use the first variant (or product price) as the base price and update total price on quantity change.
Here is the fixed updatePriceInfo() function:
function updatePriceInfo() {
if (!currentProductData) return;
const discountPriceInfoEl = $('#spec-modal-discount-price-info');
// For products without multiple variants (no spec selection)
if (!currentProductData.hasMultipleVariants) {
const qty = parseInt(qtyInput.val()) || 1;
const minQty = Number(currentProductData.min) || 1;
const maxQty = Number(currentProductData.max) || Infinity;
const isQtyValid = qty >= minQty && qty <= maxQty;
if (!isQtyValid) {
discountPriceInfoEl.hide();
return;
}
discountPriceInfoEl.show();
let variant = null;
if (currentProductData.variants && currentProductData.variants.length > 0) {
variant = currentProductData.variants[0];
}
// If no variant info, try to fallback to product-level price
const originalPrice = variant ? Number(variant.price) || 0 : Number(currentProductData.price) || 0;
const specialPrice = variant ? Number(variant.special_price) || originalPrice : originalPrice;
const discountPercent = originalPrice > 0 && specialPrice < originalPrice
? Math.round((1 - specialPrice / originalPrice) * 100)
: 0;
const totalPrice = specialPrice * qty;
function formatHKD(price) {
return 'HK$' + price.toFixed(2);
}
$('#spec-modal-unit-price').text(formatHKD(specialPrice));
$('#spec-modal-discount-percent').text(discountPercent > 0 ? `-${discountPercent}%` : '無折扣');
$('#spec-modal-total-price').text(formatHKD(totalPrice));
return;
}
// For products WITH multiple variants (need spec selection)
// Find selected attributes
let selectedAttributes = {};
let allSelected = true;
variantsContainer.find('.spec-modal-variant-group').each(function () {
const attrName = $(this).data('variant-attribute');
const checkedInput = $(this).find('input[type=radio]:checked');
if (checkedInput.length === 0) {
allSelected = false;
return false;
}
selectedAttributes[attrName] = checkedInput.val();
});
const qty = parseInt(qtyInput.val()) || 1;
const minQty = Number(currentProductData.min) || 1;
const maxQty = Number(currentProductData.max) || Infinity;
const isQtyValid = qty >= minQty && qty <= maxQty;
if (!allSelected || !isQtyValid) {
discountPriceInfoEl.hide();
return;
}
discountPriceInfoEl.show();
// Find matched variant
let matchedVariant = currentProductData.variants.find(variant => {
if (!variant.attr_name || !variant.variant_values) return false;
const attrNames = variant.attr_name.split(',').map(s => s.trim());
const attrValues = variant.variant_values.split(',').map(s => s.trim());
for (let i = 0; i < attrNames.length; i++) {
if (selectedAttributes[attrNames[i]] !== attrValues[i]) return false;
}
return true;
});
if (!matchedVariant) {
$('#spec-modal-unit-price').text('—');
$('#spec-modal-discount-percent').text('—');
$('#spec-modal-total-price').text('—');
return;
}
const originalPrice = Number(matchedVariant.price) || 0;
const specialPrice = Number(matchedVariant.special_price) || originalPrice;
const discountPercent = originalPrice > 0 && specialPrice < originalPrice
? Math.round((1 - specialPrice / originalPrice) * 100)
: 0;
const totalPrice = specialPrice * qty;
function formatHKD(price) {
return 'HK$' + price.toFixed(2);
}
$('#spec-modal-unit-price').text(formatHKD(specialPrice));
$('#spec-modal-discount-percent').text(discountPercent > 0 ? `-${discountPercent}%` : '無折扣');
$('#spec-modal-total-price').text(formatHKD(totalPrice));
}
Summary of changes:
If hasMultipleVariants is false, directly read first variant or product price.
Validate quantity min/max before showing price info.
Show and update unit price, discount, total price with qty changes.
If multiple variants, the previous logic is preserved.
This should fix the behavior so that products without specs:
Show price info immediately.
Update total price as user changes quantity.
Let me know if you want me to integrate this into your full code or help with anything else!
Sorry I have updated the updatePriceInfo before:
function updatePriceInfo() {
if (!currentProductData) return;
// Find selected attributes
let selectedAttributes = {};
let allSelected = true;
variantsContainer.find('.spec-modal-variant-group').each(function () {
const attrName = $(this).data('variant-attribute');
const checkedInput = $(this).find('input[type=radio]:checked');
if (checkedInput.length === 0) {
allSelected = false;
return false;
}
selectedAttributes[attrName] = checkedInput.val();
});
const qty = parseInt(qtyInput.val()) || 1;
// Also check quantity is valid and >= min
const minQty = Number(currentProductData.min) || 1;
const maxQty = Number(currentProductData.max) || Infinity;
const isQtyValid = qty >= minQty && qty <= maxQty;
const discountPriceInfoEl = $('#spec-modal-discount-price-info');
if (!allSelected || !isQtyValid) {
// Hide price info section if incomplete
discountPriceInfoEl.hide();
return;
}
discountPriceInfoEl.show();
// Find matched variant
let matchedVariant = currentProductData.variants.find(variant => {
if (!variant.attr_name || !variant.variant_values) return false;
const attrNames = variant.attr_name.split(',').map(s => s.trim());
const attrValues = variant.variant_values.split(',').map(s => s.trim());
for (let i = 0; i < attrNames.length; i++) {
if (selectedAttributes[attrNames[i]] !== attrValues[i]) return false;
}
return true;
});
const unitPriceEl = $('#spec-modal-unit-price');
const discountPercentEl = $('#spec-modal-discount-percent');
const discountAmountEl = $('#spec-modal-discount-amount');
const discountPriceE1 = $('#spec-modal-discount-price');
const totalPriceEl = $('#spec-modal-total-price');
if (!matchedVariant) {
unitPriceEl.text('—');
discountPercentEl.text('—');
discountAmountEl.text('—');
discountPriceE1.text('—');
totalPriceEl.text('—');
return;
}
const originalPrice = Number(matchedVariant.price) || 0;
const specialPrice = Number(matchedVariant.special_price) || originalPrice;
const discountAmount = Math.abs((specialPrice - originalPrice) * qty)
const discountPercent = originalPrice > 0 && specialPrice < originalPrice
? Math.round((1 - specialPrice / originalPrice) * 100)
: 0;
const totalPrice = specialPrice * qty;
function formatHKD(price) {
return 'HK$' + price.toFixed(2);
}
unitPriceEl.text(formatHKD(originalPrice));
discountAmountEl.text(discountAmount > 0 ? formatHKD(discountAmount) : "—");
discountPercentEl.text(discountPercent > 0 ? `-${discountPercent}%` : '無折扣');
discountPriceE1.text(formatHKD(specialPrice));
totalPriceEl.text(formatHKD(totalPrice));
}
Please integrate your change with the above version
Certainly! I'll integrate the handling for products without specs (no multiple variants) into your updated updatePriceInfo() version, preserving your discount amount and extra fields (#spec-modal-discount-amount, #spec-modal-discount-price), and showing/hiding the price info container properly.
Updated updatePriceInfo() with no-spec product support:
function updatePriceInfo() {
if (!currentProductData) return;
const discountPriceInfoEl = $('#spec-modal-discount-price-info');
// Get quantity and validate
const qty = parseInt(qtyInput.val()) || 1;
const minQty = Number(currentProductData.min) || 1;
const maxQty = Number(currentProductData.max) || Infinity;
const isQtyValid = qty >= minQty && qty <= maxQty;
// Handle products WITHOUT multiple variants (no spec selection)
if (!currentProductData.hasMultipleVariants) {
if (!isQtyValid) {
discountPriceInfoEl.hide();
return;
}
discountPriceInfoEl.show();
let variant = null;
if (currentProductData.variants && currentProductData.variants.length > 0) {
variant = currentProductData.variants[0];
}
// Use variant price if available, else fallback to product price
const originalPrice = variant ? Number(variant.price) || 0 : Number(currentProductData.price) || 0;
const specialPrice = variant ? Number(variant.special_price) || originalPrice : originalPrice;
const discountAmount = Math.abs((specialPrice - originalPrice) * qty);
const discountPercent = originalPrice > 0 && specialPrice < originalPrice
? Math.round((1 - specialPrice / originalPrice) * 100)
: 0;
const totalPrice = specialPrice * qty;
function formatHKD(price) {
return 'HK$' + price.toFixed(2);
}
$('#spec-modal-unit-price').text(formatHKD(originalPrice));
$('#spec-modal-discount-amount').text(discountAmount > 0 ? formatHKD(discountAmount) : "—");
$('#spec-modal-discount-percent').text(discountPercent > 0 ? `-${discountPercent}%` : '無折扣');
$('#spec-modal-discount-price').text(formatHKD(specialPrice));
$('#spec-modal-total-price').text(formatHKD(totalPrice));
return;
}
// Handle products WITH multiple variants (spec selection)
let selectedAttributes = {};
let allSelected = true;
variantsContainer.find('.spec-modal-variant-group').each(function () {
const attrName = $(this).data('variant-attribute');
const checkedInput = $(this).find('input[type=radio]:checked');
if (checkedInput.length === 0) {
allSelected = false;
return false;
}
selectedAttributes[attrName] = checkedInput.val();
});
if (!allSelected || !isQtyValid) {
discountPriceInfoEl.hide();
return;
}
discountPriceInfoEl.show();
let matchedVariant = currentProductData.variants.find(variant => {
if (!variant.attr_name || !variant.variant_values) return false;
const attrNames = variant.attr_name.split(',').map(s => s.trim());
const attrValues = variant.variant_values.split(',').map(s => s.trim());
for (let i = 0; i < attrNames.length; i++) {
if (selectedAttributes[attrNames[i]] !== attrValues[i]) return false;
}
return true;
});
const unitPriceEl = $('#spec-modal-unit-price');
const discountPercentEl = $('#spec-modal-discount-percent');
const discountAmountEl = $('#spec-modal-discount-amount');
const discountPriceE1 = $('#spec-modal-discount-price');
const totalPriceEl = $('#spec-modal-total-price');
if (!matchedVariant) {
unitPriceEl.text('—');
discountPercentEl.text('—');
discountAmountEl.text('—');
discountPriceE1.text('—');
totalPriceEl.text('—');
return;
}
const originalPrice = Number(matchedVariant.price) || 0;
const specialPrice = Number(matchedVariant.special_price) || originalPrice;
const discountAmount = Math.abs((specialPrice - originalPrice) * qty);
const discountPercent = originalPrice > 0 && specialPrice < originalPrice
? Math.round((1 - specialPrice / originalPrice) * 100)
: 0;
const totalPrice = specialPrice * qty;
function formatHKD(price) {
return 'HK$' + price.toFixed(2);
}
unitPriceEl.text(formatHKD(originalPrice));
discountAmountEl.text(discountAmount > 0 ? formatHKD(discountAmount) : "—");
discountPercentEl.text(discountPercent > 0 ? `-${discountPercent}%` : '無折扣');
discountPriceE1.text(formatHKD(specialPrice));
totalPriceEl.text(formatHKD(totalPrice));
}
What changed?
Early check if !hasMultipleVariants:
Validate quantity range
Show/hide price info accordingly
Use the first variant or fallback to product price
Calculate discount & total based on quantity
Update all price elements (unit-price, discount-amount, discount-percent, discount-price, total-price)
Existing spec-selection logic untouched for variant products.
This will ensure:
Products without specs display correct pricing info and update on quantity changes.
Products with specs behave same as before.
Let me know if you want me to integrate other related parts (like openModal() logic or event handlers) or help with anything else!
Now I have the following html for generate the product grid:
function buildProductHTML(product_row) {
const variant_price = (product_row.variants[0].special_price > 0 && product_row.variants[0].special_price !== '')
? product_row.variants[0].special_price
: product_row.variants[0].price;
const special_price = product_row.variants[0].special_price;
const price = product_row.variants[0].price;
const name = escapeHtml(product_row.name);
const category_name = escapeHtml(product_row.category_name);
const seller_slug = escapeHtml(product_row.seller_slug);
const store_name = escapeHtml(product_row.store_name);
const slug = escapeHtml(product_row.slug);
const image_sm = escapeHtml(product_row.image_sm);
const tags_html = product_row.tags.map(tag => {
const t = escapeHtml(tag);
return `<span class="py-2 px-8 text-xs rounded-pill text-main-two-600 bg-main-two-50"><a href="<?= base_url('products/tags/') ?>${t}">${t}</a></span>`;
}).join(' ');
return `
<div class="col-6 col-md-3 col-lg-2 product-grid" data-aos="fade-up" data-aos-duration="200">
<div class="product-card h-100 rounded-16 position-relative transition-2" style="padding: 0px !important;">
<div class="product-card__thumb rounded-8 position-relative">
<a href="<?= base_url() ?>products/details/${slug}" class="w-100 h-100 flex-center">
<img src="${image_sm}" alt="${name}" class="w-auto rounded-8">
</a>
</div>
<div class="product-card__content w-100">
<div class="product-card-tags">
${tags_html}
</div>
<h6 class="title text-lg fw-semibold" style="margin-bottom: 0px !important;">
<a href="<?= base_url() ?>products/details/${slug}" class="link text-line-2" tabindex="0">${name}</a>
</h6>
<span class="py-2 px-8 text-xs rounded-pill text-main-two-600 bg-main-two-50 mt-4">
<a href="<?= base_url() ?>products/category/${category_name}">${category_name}</a>
</span>
<span class="py-2 px-8 text-xs rounded-pill text-main-two-600 bg-main-two-50 mt-4">
<a href="<?= base_url() ?>sellers/seller_details/${seller_slug}">由${store_name}提供</a>
</span>
<div class="product-card__price mt-4 mb-4">
${special_price !== '' && special_price > 0 && special_price !== price ? `<span class="text-gray-400 text-md fw-semibold text-decoration-line-through">${formatCurrency(price)}</span>` : ''}
<span class="text-heading text-md fw-semibold">${formatCurrency(variant_price)}</span>
</div>
</div>
</div>
</div>
`;
}
CSS:
/* ============================= Product Card Css Start ========================== */
.product-card {
display: flex;
flex-direction: column;
/justify-content: space-between; /
align-items: start;
}
.product-card:hover .product-card__thumb img {
transform: scale(1.05);
}
.product-card__cart{
position: absolute;
bottom: 0px;
left: 0px;
width: 100%;
}
@media screen and (max-width: 1499px) {
.product-card__cart {
font-size: 12px;
padding: 9px 12px !important;
}
}
.product-card__badge {
border-radius: 16px 0 16px 0;
}
.product-card__thumb {
/height: 232px; /
width: 100%;
transition: 0s !important;
}
.product-card__thumb img {
max-width: 160px;
width: 100%;
transition: 0.2s linear;
}
.product-card.style-two {
flex-direction: row;
}
.product-card.style-two .product-card__thumb {
width: 260px;
height: 190px;
}
.list-grid-wrapper:not(.list-view) > .product-card{
max-width: 270px !important;
}
@media screen and (max-width: 991px) {
.product-card.style-two .product-card__thumb {
width: 190px;
}
}
@media screen and (max-width: 575px) {
.product-card.style-two .product-card__thumb {
width: 124px;
}
.list-grid-wrapper:not(.list-view) > .product-card{
max-width: 100% !important;
width: 100% !important;
}
}
@media screen and (max-width: 1199px) {
.product-card__thumb {
min-height: 160px;
}
.product-card__thumb img {
max-width: 120px;
}
.product-card__content .product-card__price span {
font-size: 0.75rem !important;
}
.product-card__content .title .link {
font-size: 0.875rem;
}
.product-card__content .text-xs {
font-size: 0.625rem !important;
}
}
/* ============================= Product Card Css End ========================== */
and the display look like the image in link: https://i.ibb.co/jPG4VRfF/image.png
I want to update the grid layout with the following element by order with the possiable reponsive design:
product image from following part:
<span class="py-2 px-8 text-xs rounded-pill text-main-two-600 bg-main-two-50 mt-4">
<a href="<?= base_url() ?>sellers/seller_details/${seller_slug}">由${store_name}提供</a>
</span>
Now the display are look like not modern and I want to make the change with the requirements:
the tags display can not exceed to one line width, if the single tag exceeded please add the overflow setting with "..."; if there are more than one and also exceeded the width, please add the "+" sign and let user to see more when they click or hover (based on the devide, mobile or pc) on the + sign
the height of the grid should flexible based on the total of information height
Let's redesign the product grid HTML structure and the CSS code to follow your requirements and improve the UI with:
The order of elements as you requested.
The tags container is limited to one line with ellipsis (...) for overflow.
If more than one tag and overflow happens, show a "+" that reveals more tags on hover (desktop) or tap (mobile).
Height of the grid adapts dynamically (flexible height).
1. Updated buildProductHTML function with structural markup and necessary classes for overflow tags:
function buildProductHTML(product_row) {
const variant_price = (product_row.variants[0].special_price > 0 && product_row.variants[0].special_price !== '')
? product_row.variants[0].special_price
: product_row.variants[0].price;
const special_price = product_row.variants[0].special_price;
const price = product_row.variants[0].price;
const name = escapeHtml(product_row.name);
const category_name = escapeHtml(product_row.category_name);
const seller_slug = escapeHtml(product_row.seller_slug);
const store_name = escapeHtml(product_row.store_name);
const slug = escapeHtml(product_row.slug);
const image_sm = escapeHtml(product_row.image_sm);
const tags_html = product_row.tags.map(tag => {
const t = escapeHtml(tag);
return `<span class="spec-modal-tag"><a href="<?= base_url('products/tags/') ?>${t}" tabindex="0">${t}</a></span>`;
}).join(' ');
return `
<div class="col-6 col-md-3 col-lg-2 product-grid" data-aos="fade-up" data-aos-duration="200">
<div class="product-card h-100 rounded-16 position-relative transition-2 d-flex flex-column" style="padding: 0 !important;">
<!-- 1. Image -->
<div class="product-card__thumb rounded-8 position-relative mb-3">
<a href="<?= base_url() ?>products/details/${slug}" class="w-100 h-100 flex-center">
<img src="${image_sm}" alt="${name}" class="w-auto rounded-8">
</a>
</div>
<!-- 2. Product category tags with overflow container -->
<div class="product-card-tags-wrapper mb-2">
<div class="product-card-tags" tabindex="0" role="list" aria-label="Product tags">
${tags_html}
</div>
<button type="button" class="tags-overflow-btn" aria-label="Show more tags" aria-expanded="false">+<span class="visually-hidden">查看更多標籤</span></button>
</div>
<!-- 3. Product name -->
<h6 class="title text-lg fw-semibold mb-2" style="line-height:1.2;">
<a href="<?= base_url() ?>products/details/${slug}" class="link text-line-2" tabindex="0">${name}</a>
</h6>
<!-- 4. Info tags -->
<div class="product-info-tags d-flex flex-column gap-2 mt-auto">
<span class="info-tag py-2 px-8 text-xs rounded-pill text-main-two-600 bg-main-two-50">
<a href="<?= base_url() ?>products/category/${category_name}" tabindex="0">${category_name}</a>
</span>
<span class="info-tag py-2 px-8 text-xs rounded-pill text-main-two-600 bg-main-two-50">
<a href="<?= base_url() ?>sellers/seller_details/${seller_slug}" tabindex="0">由${store_name}提供</a>
</span>
</div>
<!-- Price -->
<div class="product-card__price mt-3 mb-2">
${special_price !== '' && special_price > 0 && special_price !== price ? `<span class="text-gray-400 text-md fw-semibold text-decoration-line-through me-1">${formatCurrency(price)}</span>` : ''}
<span class="text-heading text-md fw-semibold">${formatCurrency(variant_price)}</span>
</div>
</div>
</div>
`;
}
2. CSS for tags container with overflow and toggle button:
/* Container for tags with overflow handling */
.product-card-tags-wrapper {
position: relative;
max-width: 100%;
overflow: hidden;
}
/* Tags container - single line flex */
.product-card-tags {
display: flex;
gap: 6px;
flex-wrap: nowrap;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 100%;
align-items: center;
}
/* Individual tag styling */
.spec-modal-tag {
flex-shrink: 0;
white-space: nowrap;
background-color: #eef2f7; /* adjust or keep from original */
color: #2563eb;
padding: 2px 8px;
border-radius: 16px;
font-size: 0.75rem; /* text-xs */
cursor: pointer;
user-select: none;
}
.spec-modal-tag a {
color: inherit;
text-decoration: none;
}
.spec-modal-tag a:hover,
.spec-modal-tag a:focus {
text-decoration: underline;
}
/* Tags overflow toggle button */
.tags-overflow-btn {
position: absolute;
right: 0;
top: 50%;
transform: translateY(-50%);
background-color: #2563eb;
border: none;
color: white;
border-radius: 50%;
width: 24px;
height: 24px;
font-weight: 700;
cursor: pointer;
display: none; /* hidden by default */
align-items: center;
justify-content: center;
font-size: 0.9rem;
line-height: 1;
padding: 0;
user-select: none;
z-index: 10;
}
/* Show button when overflow exists */
.product-card-tags-wrapper.overflowing .tags-overflow-btn {
display: flex;
}
/* When expanded, allow tags container to wrap and show all */
.product-card-tags-wrapper.expanded .product-card-tags {
flex-wrap: wrap;
white-space: normal;
overflow: visible;
text-overflow: clip;
max-height: 200px; /* optional max height for expanded state */
padding-right: 8px; /* to avoid clipping last tag */
}
/* Rotate the + button when expanded (optional) */
.product-card-tags-wrapper.expanded .tags-overflow-btn {
transform: translateY(-50%) rotate(45deg); /* + becomes x */
}
/* Accessibility hidden text */
.visually-hidden {
position: absolute !important;
height: 1px; width: 1px;
overflow: hidden;
clip: rect(1px,1px,1px,1px);
white-space: nowrap;
}
/* Product info tags should use spacing */
.product-info-tags {
gap: 8px;
}
/* Make info tags smaller on small devices */
@media (max-width: 575.98px) {
.product-card-tags {
font-size: 0.625rem;
}
.spec-modal-tag {
font-size: 0.625rem;
padding: 1px 6px;
}
.info-tag {
font-size: 0.625rem;
padding: 4px 8px;
}
}
3. JS logic to handle overflow detection and toggle expand/collapse of tags:
Add this JS snippet after you load/render the product grid . It uses plain JS or jQuery based on your environment for detecting overflow and controlling the toggle button:
function initTagsOverflow() {
const wrappers = document.querySelectorAll('.product-card-tags-wrapper');
wrappers.forEach(wrapper => {
const tagsContainer = wrapper.querySelector('.product-card-tags');
const toggleBtn = wrapper.querySelector('.tags-overflow-btn');
if (!tagsContainer || !toggleBtn) return;
// Check if tags container is overflowing horizontally
const isOverflowing = tagsContainer.scrollWidth > tagsContainer.clientWidth + 1;
if (isOverflowing) {
wrapper.classList.add('overflowing');
toggleBtn.style.display = 'flex';
} else {
wrapper.classList.remove('overflowing');
toggleBtn.style.display = 'none';
}
// Handle toggle click
toggleBtn.addEventListener('click', () => {
const expanded = wrapper.classList.toggle('expanded');
toggleBtn.setAttribute('aria-expanded', expanded);
});
// Optional: close expanded on outside click (mobile UX)
document.addEventListener('click', (e) => {
if (!wrapper.contains(e.target) && wrapper.classList.contains('expanded')) {
wrapper.classList.remove('expanded');
toggleBtn.setAttribute('aria-expanded', false);
}
});
// Optional: keyboard accessibility for toggleBtn
toggleBtn.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && wrapper.classList.contains('expanded')) {
wrapper.classList.remove('expanded');
toggleBtn.setAttribute('aria-expanded', false);
toggleBtn.focus();
}
});
});
}
// Run it once after product grid rendered:
initTagsOverflow();
// If products are dynamically loaded, call initTagsOverflow() each time after render.
4. Notes
Height Flexible: The .product-card container uses d-flex flex-column so the height depends on the total content height, which can grow if tags expand.
Accessibility: Added aria-labels, roles, keyboard support.
Overflow Detection: uses scrollWidth vs clientWidth check.
Expandable Tags: On desktop you click the "+" button, tags expand to multiple lines; button toggles to "×" (rotated +).
Mobile: You can tap + to expand, tap outside to close.
Summary
Updated HTML structure for correct order and semantic markup.
Styled product tags container for 1-line ellipsis + overflow "+" button.
Added JS logic controlling overflow detection and toggle behavior.
Product grid height automatic based on content.
If you want me to produce a runnable snippet or integrate this with your existing code, just say!
Copy first response
Not yet included in a published release.