Skip to content
TheChatArchiveThe Chat Archive
gpt-4.1-mini-2025-04-14· OpenAIAi2 WildChat-4.8M (AI2)

const containers = document.querySelectorAll('.seller-list-tag-container');…

  1. User

    const containers = document.querySelectorAll('.seller-list-tag-container');

    containers.forEach(container => { // Clear container content in case of re-render container.innerHTML = '';

    const categories_combined = container.getAttribute('data-categories') || ""; const categoriesArray = categories_combined.split(",").map(cat => cat.trim()).filter(cat => cat.length > 0);

    // An array to store tags for measurement purpose const tags = categoriesArray.map(cat => { const tag = document.createElement("div"); tag.className = "seller-list-tag-tag"; tag.textContent = cat; container.appendChild(tag); return tag; });

    // Create toggle button but don't add yet const toggleBtn = document.createElement("div"); toggleBtn.className = "seller-list-tag-toggle"; toggleBtn.style.cursor = "pointer"; toggleBtn.style.userSelect = "none"; toggleBtn.style.padding = "6px 14px"; toggleBtn.style.borderRadius = "6px"; toggleBtn.style.backgroundColor = "#121535"; toggleBtn.style.color = "white"; toggleBtn.style.fontSize = "14px"; toggleBtn.style.whiteSpace = "nowrap"; toggleBtn.style.transition = "background-color 0.3s"; toggleBtn.addEventListener("mouseenter", () => { toggleBtn.style.backgroundColor = "#1e2759"; }); toggleBtn.addEventListener("mouseleave", () => { toggleBtn.style.backgroundColor = "#121535"; });

    // Function to check how many tags can fit function updateTags() { const containerWidth = container.clientWidth - 10; // little margin for safety let usedWidth = 0; const toggleBtnWidth = 60; // arbitrary default, will measure dynamically later let lastVisibleIndex = -1;

    // Reset all tags to be visible first
    tags.forEach(t => t.style.display = "inline-flex");
    
    // Insert toggle button temporarily for measurement if not in DOM
    if (!container.contains(toggleBtn)) {
      container.appendChild(toggleBtn);
    }
    // Measure toggle button width with current text
    toggleBtn.style.display = 'inline-flex';
    toggleBtn.textContent = ''; // reset
    toggleBtn.textContent = '+99'; // temp large to get accurate width
    const measuredToggleBtnWidth = toggleBtn.offsetWidth;
    
    // Hide toggle button initially, we'll add it only if needed
    toggleBtn.style.display = 'none';
    
    // Calculate how many tags fit, taking toggle button width into account
    for (let i = 0; i < tags.length; i++) {
      const tagWidth = tags[i].offsetWidth + 8; // include gap between tags (using 8px from CSS gap property)
      if (usedWidth + tagWidth <= containerWidth) {
        usedWidth += tagWidth;
        lastVisibleIndex = i;
      } else {
        break;
      }
    }
    
    // If all fit, no toggle needed
    if (lastVisibleIndex === tags.length - 1) {
      // show all tags, hide toggle button
      tags.forEach(t => t.style.display = "inline-flex");
      toggleBtn.style.display = 'none';
      toggleBtn.removeEventListener('click', onToggleClick);
      toggleBtn.dataset.open = 'false';
      return;
    }
    
    // Otherwise, reserve space for toggle button
    usedWidth = 0;
    lastVisibleIndex = -1;
    for (let i = 0; i < tags.length; i++) {
      const tagWidth = tags[i].offsetWidth + 8;
      if (usedWidth + tagWidth + measuredToggleBtnWidth <= containerWidth) {
        usedWidth += tagWidth;
        lastVisibleIndex = i;
      } else {
        break;
      }
    }
    
    // Show visible tags, hide others
    tags.forEach((t, idx) => {
      if (idx <= lastVisibleIndex) {
        t.style.display = "inline-flex";
      } else {
        t.style.display = "none";
      }
    });
    
    const hiddenCount = tags.length - lastVisibleIndex - 1;
    toggleBtn.textContent = `+${hiddenCount}`;
    toggleBtn.style.display = 'inline-flex';
    toggleBtn.dataset.open = 'false';
    
    // Add toggle button at the end (if not already)
    if (!container.contains(toggleBtn)) {
      container.appendChild(toggleBtn);
    }
    

    }

    function onToggleClick() { const isOpen = toggleBtn.dataset.open === 'true'; if (isOpen) { // Collapse toggleBtn.dataset.open = 'false'; updateTags(); } else { // Expand all tags.forEach(t => t.style.display = "inline-flex"); toggleBtn.dataset.open = 'true'; toggleBtn.textContent = '−'; // minus sign } }

    toggleBtn.addEventListener('click', onToggleClick);

    // On window resize recalc tags fitting window.addEventListener('resize', () => { if (toggleBtn.dataset.open !== 'true') { updateTags(); } });

    updateTags(); });

    .seller-list-tag-container { display: flex; flex-wrap: wrap; gap: 8px; padding: 0px 10px 0px 0px; max-width: 100%; /* 最大寬度,避免太撐 */ margin: -10px auto; }

    /* Tag基礎造型 */ .seller-list-tag-tag { background-color: #121535; color: white; border-radius: 6px; padding: 6px 14px; font-size: 14px; white-space: nowrap; user-select: none; cursor: default; transition: background-color 0.3s; } .seller-list-tag-tag:hover { background-color: #1e2759; }

    /* 響應式調整字體大小與間距 */ @media (max-width: 1024px) { .seller-list-tag-container { max-width: 90vw; } .seller-list-tag-tag { font-size: 13px; padding: 5px 12px; } }

    @media (max-width: 600px) { .seller-list-tag-tag { font-size: 12px; padding: 4px 10px; } }

    .seller-list-tag-toggle { background-color: #121535; color: white; border-radius: 6px; padding: 6px 14px; font-size: 14px; white-space: nowrap; user-select: none; cursor: pointer; transition: background-color 0.3s; display: inline-flex; align-items: center; justify-content: center; margin-left: 4px; } .seller-list-tag-toggle:hover { background-color: #1e2759; }

    The above codes will used to display the categories of the seller in the online shop. When tags display exceed the width of container, the remaining tags will collapsed and the + button will appear for user to click to see more tags. There are problems when display more than on seller on the page together, and the tags except the first seller will all collapsed by default. Please help me to fix it

  2. Assistant

    The issue you describe:

    When displaying more than one seller's tags on the page, only the first seller's tags show fully, all others collapse by default, even if they have enough space.

    This is a common problem when the script uses only one toggle button element (toggleBtn) per container in the loop, but if there's any closure or shared reference issue, or if event listeners are somehow conflicting, it can cause improper handling of multiple containers.

    Looking at your code, you create a toggleBtn inside the .forEach(container => {...}). So each container should have its own toggle button, which is good.

    However, possible causes of the problem:

    1. Multiple containers share the same toggleBtn event listener or state?
      But since toggleBtn is const toggleBtn = document.createElement("div"); inside the forEach, it should be unique per container.

    2. window.addEventListener('resize', ... ) being added multiple times may cause conflicts across containers.
      Each container adds an event listener on window resize, updating its own tags, so it should be fine, but could be optimized.

    3. tags[i].offsetWidth measurement may be 0 or improper for tags not yet rendered.
      This can cause calculation issues and wrong fitting computations.

    4. container.clientWidth might be 0 or incorrect if the container is hidden or styled in a way delaying rendering.

    5. toggleBtn display toggling and measurement may be inconsistent.

    6. Initial measuring right after emptying container (before tag elements are fully rendered)

    7. CSS margin or padding messing measurement


    What I suspect more specifically:

    • Your code is correct in principle, but the updateTags() function relies on measurements of elements immediately after elements are created/appended and style changes. Sometimes measurements return 0 or inconsistent values if the DOM hasn't painted yet.

    • The toggleBtn width is set with toggleBtn.textContent = '+99' dynamically, then measured. But sometimes it may not be correctly updated or measured if the DOM hasn't updated.

    • For multiple containers, the tags elements might not be visible/measurable for some containers at initial script execution, especially if styles or layout hasn't finalized.


    How to fix:

    Option A: Add a small delay (e.g., via requestAnimationFrame or setTimeout) before measuring widths, so browser can render new elements properly and measurements are accurate.

    Option B: Make sure toggle button is appended before measuring, or at least measure after DOM updated.

    Option C: Avoid re-adding toggle button multiple times inside the container, or create one per container guaranteed.


    Applying Option A:

    Change:

    updateTags();
    

    to:

    requestAnimationFrame(updateTags);
    

    or

    setTimeout(updateTags, 0);
    

    to allow the DOM to paint before measurements occur.


    Also, change your resize event listener to debounce or throttle so multiple rapid calls don't cause trouble.


    Another note:

    You currently add the resize event listener inside the loop for each container like:

    window.addEventListener('resize', () => {
        if (toggleBtn.dataset.open !== 'true') {
          updateTags();
        }
    });
    

    But this means multiple listeners for the entire window – better to register one listener outside looping over containers, which will update all containers accordingly.


    Suggestion: Revised approach for multiple containers

    1. Create a function to initialize each container and keep its own toggleBtn/tags update.

    2. Store references in an array.

    3. On window resize event, iterate all containers and call updateTags only if toggleBtn is not expanded.


    Full Working Revised Example:

    const containers = document.querySelectorAll('.seller-list-tag-container');
    
    const sellers = [];
    
    containers.forEach(container => {
      // Clear container content in case of re-render
      container.innerHTML = '';
    
      const categories_combined = container.getAttribute('data-categories') || "";
      const categoriesArray = categories_combined.split(",").map(cat => cat.trim()).filter(cat => cat.length > 0);
    
      // Create tag elements
      const tags = categoriesArray.map(cat => {
        const tag = document.createElement("div");
        tag.className = "seller-list-tag-tag";
        tag.textContent = cat;
        container.appendChild(tag);
        return tag;
      });
    
      // Create toggle button
      const toggleBtn = document.createElement("div");
      toggleBtn.className = "seller-list-tag-toggle";
      toggleBtn.style.cursor = "pointer";
      toggleBtn.style.userSelect = "none";
      toggleBtn.style.padding = "6px 14px";
      toggleBtn.style.borderRadius = "6px";
      toggleBtn.style.backgroundColor = "#121535";
      toggleBtn.style.color = "white";
      toggleBtn.style.fontSize = "14px";
      toggleBtn.style.whiteSpace = "nowrap";
      toggleBtn.style.transition = "background-color 0.3s";
      toggleBtn.style.display = 'none';  // start hidden
      toggleBtn.addEventListener("mouseenter", () => {
        toggleBtn.style.backgroundColor = "#1e2759";
      });
      toggleBtn.addEventListener("mouseleave", () => {
        toggleBtn.style.backgroundColor = "#121535";
      });
      container.appendChild(toggleBtn);
    
      function updateTags() {
        const containerWidth = container.clientWidth - 10; // small safe margin
        let usedWidth = 0;
        // Measure toggleBtn with dummy text
        toggleBtn.style.display = 'inline-flex';
        toggleBtn.textContent = '+99';
        const toggleBtnWidth = toggleBtn.offsetWidth;
        toggleBtn.style.display = 'none';
    
        // Reset to show all tags initially
        tags.forEach(t => {
          t.style.display = "inline-flex";
        });
    
        // First, check if all tags fit without toggle
        let lastVisibleIndex = -1;
        for (let i = 0; i < tags.length; i++) {
          const tagWidth = tags[i].offsetWidth + 8; // 8px gap
          if (usedWidth + tagWidth <= containerWidth) {
            usedWidth += tagWidth;
            lastVisibleIndex = i;
          } else {
            break;
          }
        }
    
        if (lastVisibleIndex === tags.length - 1) {
          // All tags fit, hide toggle button
          tags.forEach(t => t.style.display = 'inline-flex');
          toggleBtn.style.display = 'none';
          toggleBtn.dataset.open = 'false';
          toggleBtn.textContent = '';
          return;
        }
    
        // Need toggle, reserve toggleBtn width
        usedWidth = 0;
        lastVisibleIndex = -1;
        for (let i = 0; i < tags.length; i++) {
          const tagWidth = tags[i].offsetWidth + 8;
          if (usedWidth + tagWidth + toggleBtnWidth <= containerWidth) {
            usedWidth += tagWidth;
            lastVisibleIndex = i;
          } else {
            break;
          }
        }
    
        // Show tags up to lastVisibleIndex
        tags.forEach((t, idx) => {
          t.style.display = idx <= lastVisibleIndex ? 'inline-flex' : 'none';
        });
    
        const hiddenCount = tags.length - lastVisibleIndex - 1;
        toggleBtn.textContent = `+${hiddenCount}`;
        toggleBtn.dataset.open = 'false';
        toggleBtn.style.display = 'inline-flex';
      }
    
      function onToggleClick() {
        const isOpen = toggleBtn.dataset.open === 'true';
        if (isOpen) {
          toggleBtn.dataset.open = 'false';
          updateTags();
        } else {
          tags.forEach(t => t.style.display = 'inline-flex');
          toggleBtn.dataset.open = 'true';
          toggleBtn.textContent = '−'; // minus sign
        }
      }
      toggleBtn.addEventListener('click', onToggleClick);
    
      // Store container info for global resize handler
      sellers.push({ container, tags, toggleBtn, updateTags });
    
      // Initially delay updateTags for DOM stable measurement
      requestAnimationFrame(updateTags);
    });
    
    // Global window resize handler only once
    window.addEventListener('resize', () => {
      sellers.forEach(({ toggleBtn, updateTags }) => {
        if (toggleBtn.dataset.open !== 'true') {
          // Only recalc if not expanded
          requestAnimationFrame(updateTags);
        }
      });
    });
    

    Why this works better:

    • The toggle button is appended once per container.

    • updateTags runs on next animation frame after initial DOM change, ensuring accurate measurement.

    • The window resize event listener updates all containers properly.

    • Measurements and toggling are done per container separately.


    Bonus: CSS notes

    Your current CSS is mostly okay. Your question does not indicate CSS problems.

    BUT, you should ensure .seller-list-tag-container has a defined width (or max-width) and layout.


    If you want me to help you improve or refactor the code further, please let me know.

  3. User

    FYI, the tags will displayed in the page that list out all sellers, so that there are not only one seller's categories will be show on screen. But the current solution is assumed that there is only one seller show on screen. So please update the solution

  4. Assistant

    Thanks for the clarification!

    The core issue, as you noted, is:

    • There are multiple sellers on the page, each with their own .seller-list-tag-container.
    • Each container needs its own independent toggle button, tags, and updating logic.
    • The current solution I provided *collects all containers and adds a single resize event listener that re-runs update for all.
    • The main challenge is ensuring each container manages its own toggle and render properly without interference.

    Updated solution that works properly for multiple sellers:

    • Each .seller-list-tag-container creates its own set of tags and its own toggle button.
    • Each container maintains its own updateTags() and onToggleClick() methods with distinct closures.
    • On window resize, update all sellers individually.
    • Use a global array sellers to store each container’s data (container, tags, toggleBtn, updateTags).
    • Debounce resize event for performance.

    Full updated code:

    (() => {
      const containers = document.querySelectorAll('.seller-list-tag-container');
    
      const sellers = [];
    
      containers.forEach(container => {
        // Clear container in case of re-render
        container.innerHTML = '';
    
        const categories_combined = container.getAttribute('data-categories') || "";
        const categoriesArray = categories_combined.split(",").map(cat => cat.trim()).filter(cat => cat.length > 0);
    
        // Create tag elements
        const tags = categoriesArray.map(cat => {
          const tag = document.createElement("div");
          tag.className = "seller-list-tag-tag";
          tag.textContent = cat;
          container.appendChild(tag);
          return tag;
        });
    
        // Create toggle button
        const toggleBtn = document.createElement("div");
        toggleBtn.className = "seller-list-tag-toggle";
        toggleBtn.style.cursor = "pointer";
        toggleBtn.style.userSelect = "none";
        toggleBtn.style.padding = "6px 14px";
        toggleBtn.style.borderRadius = "6px";
        toggleBtn.style.backgroundColor = "#121535";
        toggleBtn.style.color = "white";
        toggleBtn.style.fontSize = "14px";
        toggleBtn.style.whiteSpace = "nowrap";
        toggleBtn.style.transition = "background-color 0.3s";
        toggleBtn.style.display = 'none'; // start hidden
        toggleBtn.addEventListener("mouseenter", () => {
          toggleBtn.style.backgroundColor = "#1e2759";
        });
        toggleBtn.addEventListener("mouseleave", () => {
          toggleBtn.style.backgroundColor = "#121535";
        });
    
        container.appendChild(toggleBtn);
    
        // Flag to prevent measurement while expanded
        let isExpanded = false;
    
        function updateTags() {
          if (isExpanded) {
            return; // don’t update while expanded
          }
    
          const containerWidth = container.clientWidth - 10; // small margin buffer
          let usedWidth = 0;
    
          // Show all tags initially for measurement
          tags.forEach(t => t.style.display = "inline-flex");
    
          // Show toggle button temporarily with dummy text for width measurement
          toggleBtn.style.display = 'inline-flex';
          toggleBtn.textContent = '+99';
          const toggleBtnWidth = toggleBtn.offsetWidth || 40; // fallback on 40px if 0
    
          // Hide toggle button until needed
          toggleBtn.style.display = 'none';
    
          let lastVisibleIndex = -1;
    
          // First try if all tags fit without toggle
          for (let i = 0; i < tags.length; i++) {
            const tagWidth = tags[i].offsetWidth + 8; // 8px gap assumed
            if (usedWidth + tagWidth <= containerWidth) {
              usedWidth += tagWidth;
              lastVisibleIndex = i;
            } else {
              break;
            }
          }
    
          if (lastVisibleIndex === tags.length - 1) {
            // All tags fit, show all, hide toggle button
            tags.forEach(t => t.style.display = "inline-flex");
            toggleBtn.style.display = 'none';
            toggleBtn.textContent = '';
            toggleBtn.dataset.open = 'false';
            isExpanded = false;
            return;
          }
    
          // Need toggle button, reserve space for it
          usedWidth = 0;
          lastVisibleIndex = -1;
          for (let i = 0; i < tags.length; i++) {
            const tagWidth = tags[i].offsetWidth + 8;
            if (usedWidth + tagWidth + toggleBtnWidth <= containerWidth) {
              usedWidth += tagWidth;
              lastVisibleIndex = i;
            } else {
              break;
            }
          }
    
          // Show only fitting tags, hide rest
          tags.forEach((t, idx) => {
            t.style.display = idx <= lastVisibleIndex ? "inline-flex" : "none";
          });
    
          const hiddenCount = tags.length - lastVisibleIndex - 1;
          toggleBtn.textContent = `+${hiddenCount}`;
          toggleBtn.style.display = 'inline-flex';
          toggleBtn.dataset.open = 'false';
          isExpanded = false;
        }
    
        function onToggleClick() {
          const isOpen = toggleBtn.dataset.open === 'true';
          if (isOpen) {
            // Collapse tags
            toggleBtn.dataset.open = 'false';
            isExpanded = false;
            updateTags();
          } else {
            // Expand all tags
            tags.forEach(t => t.style.display = "inline-flex");
            toggleBtn.dataset.open = 'true';
            toggleBtn.textContent = '−'; // minus sign
            toggleBtn.style.display = 'inline-flex';
            isExpanded = true;
          }
        }
        toggleBtn.addEventListener('click', onToggleClick);
    
        // Store seller info for resize updates
        sellers.push({ updateTags, toggleBtn });
    
        // Initial update after DOM render for accurate measurement
        requestAnimationFrame(updateTags);
      });
    
      // Debounce function for resize event
      function debounce(func, wait) {
        let timeout;
        return function() {
          clearTimeout(timeout);
          timeout = setTimeout(() => {
            func();
          }, wait);
        };
      }
    
      const onResize = debounce(() => {
        sellers.forEach(({ updateTags, toggleBtn }) => {
          if (toggleBtn.dataset.open !== 'true') {
            updateTags();
          }
        });
      }, 100);
    
      window.addEventListener('resize', onResize);
    })();
    

    Explaining the changes & benefits:

    • Closure per seller: Each container keeps its own references for tags, toggleBtn, and updateTags.
    • Global resize handler updates all sellers with their own updateTags function.
    • isExpanded flag per seller prevents recalculation while tags are expanded.
    • Debounced resize event for performance on many sellers.
    • Use requestAnimationFrame(updateTags) initially so measurements happen after DOM paints.
    • Append toggle button once per container only.
    • Use a fallback width if toggleBtn's offsetWidth is zero.

    This approach works well with multiple sellers, each with their independent tags and toggle button behavior, and adapts correctly on window resize.


    If you want me to integrate this with your existing CSS or further optimize it, feel free to ask!

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.