My objective has been to build a custom dropdown like the one on Amazon's search scope selector. I do this by positioning a styleable element on top of a standard select list. I then use jQuery to keep the styleable element in sync with the select list. My code works fine, but I would love to learn how to do it cleaner. Currently I do the syncing twice - on page load and on change. Is it possible to refactor my code using on()? (or similar).
prev() is the styleable element.
// Sync is performed on page load
var $select = $('select');
$select.each(function(index, value) {
var optionText = $(this).find('option:selected').text();
$(this).prev().text(optionText);
});
// Sync is performed on change event
$('select').change(function() {
var optionText = $(this).find('option:selected').text();
$(this).prev().text(optionText);
});