fbpx
Want To Add Extra Images Per Product Variation For Free? Download Now

Set first variation as default on loading

I am using the variation swatches on a clothing store.
All products are variable and have a size and color attribute.

What I like to achieve is that upon loading the product – without attributes selected – the first color option is selected by default.
This works is most of our cases but we rely heavily on loading speeds of the page, which is of course causing issues. Example code provided below.

2 questions:

  1. Is there any better way of doing this? Setting a default variation from the dashboard is not an option. We manage the products in the store via an api. The way this is working in our case is preventing us from selecting a default.
  2. We face an issue when the on page cart form is still loading it’s data the code below isn’t working at all cause it’s unable to click the color as it’s not yet available. Are you aware of any events we could use to run our color picker code once the form is loaded?
<script>
jQuery(document).ready(function($) {
    function selectColorOption() {
        if ($(‘body.single-product’).length > 0) {
var $colorOption = $(‘.variable-items-wrapper[data-attribute_name=”attribute_pa_color”] li:first-child’); // Select the first li element
// Simulate a click on the color option with a delay
setTimeout(function() {
$colorOption.click();
}, 1000);
}
    }
    // Run the selectColorOption function on page load
    selectColorOption();
    // Use the pageshow event to run the selectColorOption function when the user returns to the tab
    window.addEventListener(‘pageshow’, function(event) {
        selectColorOption();
    });
});
</script>

Hakik Zaman

Hi Maarten,

Thanks for reaching out to us.

The query is beyond our support scope.

Please check our support policy.

Thank You