Magento – Auto Select colour Swatch when configurable product page loads

color-swatchesconfigurable-productjavascriptmagento-1.9

I have a configurable product with one colour and different sizes, both these are set as required fields.

I've set the colour attribute as not required, but then it wont show up when I create a configurable product and wont show on the product page.

How do I get the colour swatch to be automatically selected when the product page loads?

Best Answer

Open this file from app\design\frontend[your package][your theme]\template\catalog\product\view\type\options\configurable.phtml

Now add the below javascript code :-

 function fireEvent(element,event){
if (document.createEventObject){
// dispatch for IE
var evt = document.createEventObject();
return element.fireEvent('on'+event,evt)
}
else{
// dispatch for firefox + others
var evt = document.createEvent("HTMLEvents");
evt.initEvent(event, true, true ); // event type,bubbling,cancelable
return !element.dispatchEvent(evt);
}
}
Event.observe(window, 'load', function() {
spConfig.settings[0].selectedIndex = 1;
obj = spConfig.settings[0]; // this grabs the first select item
Event.observe(obj,'change',function(){});
fireEvent(obj,'change'); // this simulates selecting the first option, which triggers
spConfig.settings[1].selectedIndex = 1; // this selects the first option of the second attribute drop menu
});

after this code :-

var spConfig = new Product.Config(<?php echo $this->getJsonConfig() ?>);

and flush magento cache and check.