Home › Forums › JavaScript › Convert Menu to Dropdown (variation) › Re: Convert Menu to Dropdown (variation)
Try this:
(function($) {
// DOM ready
$(function() {
// Create the dropdown base
$(““).appendTo(“nav”);
// Create default option “Go to…”
$(““, {
“selected”: “selected”,
“value” : “”,
“text” : “Go to…”
}).appendTo(“nav select”);
// Populate dropdown with menu items
$(“nav > ul > li”).each(function() {
var level_1 = $(this);
var level_1_hasChildren = $(this).find(“> ul”),
level_2 = $(this).find(“> ul > li”);
if (level_1_hasChildren.length) {
$(““, {
“value” : level_1.find(“> a”).attr(“href”),
“text” : level_1.find(“> a”).text()
}).appendTo(“nav select”);
level_2.each(function() {
var level_2 = $(this);
var level_2_hasChildren = level_2.find(“> ul”),
level_3 = level_2.find(“> ul > li”);
if (level_2_hasChildren.length) {
$(““, {
“value” : $(this).find(“> a”).attr(“href”),
“text” : ‘ — ‘ + $(this).find(“> a”).text()
}).appendTo(“nav select”);
level_3.each(function() {
$(““, {
“value” : $(this).find(“> a”).attr(“href”),
“text” : ‘ —- ‘ + $(this).find(“> a”).text()
}).appendTo(“nav select”);
});
}
else
{
$(““, {
“value” : $(this).find(“> a”).attr(“href”),
“text” : ‘ — ‘ + $(this).find(“> a”).text()
}).appendTo(“nav select”);
}
});
}
else
{
$(““, {
“value” : $(this).find(“> a”).attr(“href”),
“text” : $(this).find(“> a”).text()
}).appendTo(“nav select”);
}
});
// To make dropdown actually work
$(“nav select”).change(function() {
window.location = $(this).find(“option:selected”).val();
});
});
})(jQuery);