I have some configurable products with a custom color swatches attribute. Lot of them have just one color options, so i 'd like to mark the option as selected in the product page. I added a custom js script to the product page but it works just in chrome console, not in the website. (Jquery is inthe required function, i don't know why stack's editor does not read it as code)

  var number = $('.swatch-attribute .color').length;
    $('.swatch-attribute .color').click();

It does not work and the color option it is still not selected, how can i fix it?

1 Answer 1


I suggest running that code using an on load event listener.

if (window.addEventListener) // W3C standard
  window.addEventListener('load', configurabledefaults, false); // NB **not** 'onload'
else if (window.attachEvent) // Microsoft
  window.attachEvent('onload', configurabledefaults);
function configurabledefaults {
var number = $('.swatch-attribute .color').length;
if(number==1){$('.swatch-attribute .color').click();}

See the following link about multiple onload events.

Multiple window on load events

  • thnks for the answers, i tried it in the console but it gave me and "unexpected token } error"
    – user48824
    Apr 18, 2018 at 22:18
  • You are correct, that code will not work from the console, it does however work if placed in a <script> tag on the page. Try putting it under the description field of a product. Apr 18, 2018 at 22:21
  • Ok thanks, i'll test it. it worked in your store?
    – user48824
    Apr 18, 2018 at 22:35
  • 1
    I tested that code on my staging environment and it worked. Apr 18, 2018 at 22:55

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.