treehouse : what would you like to learn today?
Web Design Web Development iOS Development

[Solved] Convert UL menu to dropdown with optgroups

  • Hi

    I realise that another user seems to have posted a similar question due to his / her similar problem, but I am trying to convert my UL menu to a dropdown, with all nested ULs converting to OptGroups - as per the example on http://css-tricks.com/examples/ConvertMenuToDropdown/optgroup.php

    It turns out, that the script used in the example (above) actually doesn't convert the links in the UL to links in the dropdown (select). The simple, unested example works. The nested one doesn't.

    Please help?

    Thanks in advance.
  • replace the script with this:
    <script>
    // DOM ready
    $(function() {

    // Create the dropdown base
    $("<select />").appendTo("nav");

    // Create default option "Go to..."
    $("<option />", {
    "selected": "selected",
    "value" : "",
    "text" : "Go to..."
    }).appendTo("nav select");

    // Populate dropdown with menu items
    $("nav > ul > li").each(function() {

    var el = $(this);

    var hasChildren = el.find("ul"),
    children = el.find("li");

    if (hasChildren.length) {

    $("<optgroup />", {
    "label": el.find("> a").text()
    }).appendTo("nav select");

    children.each(function() {

    $("<option />", {
    "text": " - " + $(this).text(),
    "value": $(this).find("> a").attr("href")
    }).appendTo("optgroup:last");

    });

    } else {

    $("<option />", {
    "value" : el.find("> a").attr("href"),
    "text" : el.text()
    }).appendTo("nav select");

    }

    });

    // To make dropdown actually work
    // To make more unobtrusive: http://css-tricks.com/4064-unobtrusive-page-changer/
    $("nav select").change(function() {
    window.location = $(this).find("option:selected").val();
    });

    });
    </script>
  • Thank you, Wolfcry. Worked like a charm. Going to go through this properly and see what was different...