A More Complex Way of Building Replacement Combo Boxes
(Page 1 of 4 )
In part one we looked at an easy way to recreate the functionality of combo boxes, while also creating the ability to style them effectively across browsers. In this part, we're going to work on getting rid of the hard coding of option values in the event handlers for the options, and look at dealing with combo boxes that have more options. You'll need the source files from part one to build on, and your trusty text editor at your side.
First of all, we can look at getting rid of the hard-coded option values that are sent to the JavaScript file in the onclick event of each element. We will still be sending a parameter, but instead of using the text that forms the option in the drop-down div, we can use the this keyword instead. Change the onclick function calls in the replacementcombos.html file to look like this (no pun intended):
<div id="combodiv">
<a class="option" href="#" onclick="setOption(this)">Option 1</a>
<a class="option" href="#" onclick="setOption(this)">Option 2</a>
<a class="option" href="#" onclick="setOption(this)">Option 3</a>
<a class="option" href="#" onclick="setOption(this)">Option 4</a>
<a class="option" href="#" onclick="setOption(this)">Option 5</a>
<a class="option" href="#" onclick="setOption(this)">Option 6</a>
<a class="option" href="#" onclick="setOption(this)">Option 7</a>
<a class="option" href="#" onclick="setOption(this)">Option 8</a>
<a class="option" href="#" onclick="setOption(this)">Option 9</a>
<a class="option" href="#" onclick="setOption(this)">Option 10</a>
</div>
Ok, so we now have no hard-coded values, just the this keyword. In this example, this refers to the element that the onclick is a property of. So when the user clicks on an option, the function is called and the parameter refers to whichever anchor element (option) was clicked instead of just being passed the text that we want to add to the text field.
We now have to use a little DOM jiggery-pokery to get at the actual text content. In the combo.js file, change the setOption() function so that it appears as follows:
function setOption(element) {
var selection = element.childNodes[0].nodeValue;
var combo = document.getElementById('combofield').value = selection;
document.getElementById('combodiv').style.display = "none";
comboopenflag = "off";
}
The text that the visitor sees as an option in the combo div is a textNode in the DOM, and appears as a child of the a element. So element.childNodes[0] refers to the first child of the a element and the actual text is contained in the nodeValue property. Other than this, the function is exactly the same as before. So we've gotten rid of the hard-coded option values and the page functions pretty much as it did before. Next we should adjust it to handle combo boxes with more options.
Next: Increasing our Options >>
More Style Sheets Articles
More By Dan Wellman