Making YUI ButtonGroups behave

I like YUI Buttons. Amongst other niceties they allow you to have reliable cross-browser, cross platform custom-rendered form widgets like checkboxes and radio buttons — while keeping all the accessibility concerns in check. One of the functionalities it has is to create “ButtonGroups”, i.e. a bunch of button controls that behave as a traditional radio-button group. All nice and good, except that it has one obnoxious behaviour: it forces all your radio buttons inside a common container — which might not be what you had in mind. I like my radio buttons where I put them, thank you…

So, quick fix coming up:

var radioGroup = new YAHOO.widget.ButtonGroup({ container: aDivSomewhereItDoesntMatterWhere });
var radioButtons = anArrayOfPlainNormalRadioButtons;

for (var i = 0, len = radioButtons.length; i < len; ++i) {

    var nodeIndex = getNodeIndex(radioButtons[i]),
        parentNode = radioButtons[i].parentNode,
        radioButton = new YAHOO.widget.Button(radioButtons[i]);

    // This will put the button somewhere silly

    // Move the button back where it was
    parentNode.insertBefore(radioButton.get("element"), parentNode.childNodes[nodeIndex]);

So, it’s more verbose than just using the simple “new YAHOO.widget.ButtonGroup(radioButtonContainer)” syntax that does everything for you — if you are willing to have the radio buttons where YUI put them. Also… what’s that “getNodeIndex()” function?, I hear you ask. Just a simple utility off my toolbox; it gets the index of a node within all the nodes with the same parent:

var nodeIndex = function(element) {
    for (var index = 0, el = element; el = el.previousSibling; ++index);
    return index;

Hope that’s helpful…

Leave a Reply