Customize product suggestions

In Tweakwise JS, Suggestions have limited customization options.

Customizing the display of product suggestions, can be achieved through event hooks:

<script>
  window.addEventListener("DOMContentLoaded", function () {
    window.tweakwiseSuggestions({  
      // ...
      on: {  
        'twn.request.products.success': function () {  
          console.log('request for fetching product suggestions succeeded');  
        },  
      },
    });
  });
</script>

Example

Adding a product_number to the product suggestions:

<script>
  function updateTwProductSuggestion(item) {
    // Find value to add to the suggestion
    const productNumber = item.attributes.find((a) => a.name === 'product_number').values[0];
        
    // Target Product Suggestion
    const el = document.body.querySelector(
      `a.twn-product-suggestion[data-item-id="${item.itemno}"]`
    );

    // Get the details container
    const container = el?.querySelector('.twn-product-suggestion__details');

    // create html string with necessary data to add
    const details =  'Productnumber: <em>' + productNumber + '</em>';

    // Check whether this element already exists so we don't duplicate them on further search
    let existingElement = container?.querySelector('.tw-product-number');
    if (!existingElement) {
      existingElement = document.createElement('div');
      existingElement.className = 'tw-product-number';
      container?.append(existingElement);
    }
    existingElement.innerHTML = details;
  }
  
  window.addEventListener("DOMContentLoaded", function () {
    window.tweakwiseSuggestions({  
      // ...
      "twn.request.products.success": function (event) {
        var hasItems = event && Array.isArray(event.items) && event.items.length > 0;  
        if (!hasItems) {
          return;
        }

        // use setTimeout to delay execution, because request can be 
        // finished before the container is opened and search elements 
        // may not be rendered yet
        setTimeout(() => {
          event.items.forEach((item) => {
            updateTwProductSuggestion(item);
          })
        }, 0)

      }
    });
  });
</script>

Need more control?

Consider integrating Suggestions using API.