Dropdown Menu Categories / Subcategories

What I am trying to do is a split dropdown menu. This example has five options, how can I categorize the dropdown? For example, do options 1 and 2 fall out of the environment category and the sports category 3 and 4 and college tier 5? http://jsfiddle.net/fc3550sk/

For example:

Reset: select when you click it Menu will be Environment, Sports, Colleges .. Then hover your mouse over the environment and it will let you choose one of options 1 or 2 ... or hover over sport and it will let you choose 3 or 4 and so on.

This is what I have so far:

      <select name="SPECIAL" id="SPECIAL">
  <option>Please Select</div>
    <option data-img="/images/img/AnimalFriend.png" value="1">AnimalFriend</option>
    <option data-img="/images/img/Aquaculture.png" value="2">Aquaculture</option>
    <option data-img="/images/img/ProtectOurOceans.png" value="3">Protect Our Oceans</option>
    <option data-img="/images/img/ConserveWildlife.png" value="4">Conserve Wildlife</option>
          </select>
      <!-- Modal -->
<div class="modal fade" id="modal_special" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">&times;</span><span class="sr-only">Close</span></button>
        <h4 class="modal-title" id="myModalLabel">Specialty Plate</h4>
      </div>
      <div class="modal-body">
        ...
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
          <button type="button" class="btn btn-primary accept">Accept</button>
      </div>
    </div>
  </div>
</div>

      


$(function() {
        $('#SPECIAL').on('change', function() {
            if ($('option:selected', this).is('[data-img]')) {
                $('#modal_special').find('.modal-body').html('<p>Image will go here:</p>')
                .append('<img alt="coming soon" src="' + $('option:selected', this).data('img') + '"/>')
                .end().modal('show');
            }
        });
        $('.accept').on('click',function() {
            //do something
            $('#modal_special').modal('hide');
        });
    });

      

Any help would be greatly appreciated!

+3


source to share


2 answers


I don't know how to hook up a "hover" event listener to the standard dropdowns, but it doesn't work too hard to implement my own dropdown with jquery, html and css.

Custom Dropdown Benefit # 01

You can assign as many custom values ​​to each entry as you like.

In your example, you have "Special Plates" and you might want to assign a price, a special code assigned to that plate, an image assigned to that plate, and so on. With the HTML / jQuery version, you can create your own dropdowns with simple tags <span>

like this:

<span data-code="SPRT01" data-image="" data-price="34.00">Sports 01</span>
<span data-code="SPRT02" data-image="" data-price="35.00">Sports 02</span>
<span data-code="SPRT03" data-image="" data-price="36.00">Sports 03</span>

      

Note that each record has three values ​​assigned to them: data code, data image, and data price. If you are using html dropdown you don't have that freedom. There are ways to expand values ​​associated with the standard dropdown, but getting values ​​is messy and you still won't be able to access the behavior that depends on your functions.

Custom Dropdown Benefit # 02

You can actually use the hover behavior.

In your example, you want "submenus" to appear when certain values ​​in the dropdown are selected, but as far as I know there is no way to access the values ​​that are "hovering" "in the standard dropdown, and search is only for the HTML solution just doesn't exist, so you'll have to use javascript one way or another.

Using jQuery you can easily get the values ​​in your custom dropdown elements like:

$("span").hover(
    function(){
        var text = $(this).text();
        console.log("You have hovered on: ", text); 
    }, 
    function(){
        // You have hovered off the span        
    }
);

      


My solution to your problem

Putting these ideas into practice, I've put together a simple demo of how you can create a custom dropdown using your application settings.



You can view the jsfiddle of the demos here.

The basic idea is that you create a hierarchy in html with the structure of your top level options (Environment, Sports, Colleges) in a div .drop_down_scroll_container

and you place all your div sub levels (Environment 01, Environment 02, etc.) below this div in class div .dropdown-subcategory

. Where the magic happens is javascript looks at the top level option index and then shows dropdown-subcategory

at that same index.

For example, in the following html snippet, you can see the index positions of each of the intervals in the drop_down_scroll_container

div:

<div class="drop_down_scroll_container">
   <span>Environment</span> <!-- index 0 -->
   <span>Sports</span>      <!-- index 1 -->
   <span>Colleges</span>    <!-- index 2 -->
</div>

      

So when you hover over any of these top-level options (Environment, Sports, Colleges), you can ask jQuery to open the corresponding submenu divs that are below the .drop_down_scroll_container

divs in div containers with class.dropdown-subcategory

<div id="dropdown" class="specialtyPlatesCategories">

    <div class="selectHeader">Click to Select Plates:</div>

    <!-- THIS IS WHERE YOU WILL PUT YOUR TOP-LEVEL OPTIONS -->
    <div class="drop_down_scroll_container">
        <span>Environment</span>
        <span>Sports</span>
        <span>Colleges</span>
    </div>

    <!-- THIS DIV IS AT INDEX 0 of: #dropdown.dropdown-subcategory  -->
    <!-- Will fade in when the drop_down_scroll_container index 0 is hovered -->
    <div id="env_subcategories" class="dropdown-subcategory">
           <span data-code="ENV01" data-image="" data-price="31.00">Environment 01</span>
       <span data-code="ENV02" data-image="" data-price="32.00">Environment 02</span>
       <span data-code="ENV03" data-image="" data-price="33.00">Environment 03</span>
    </div>

    <!-- THIS DIV IS AT INDEX 1 of: #dropdown.dropdown-subcategory  -->
    <!-- Will fade in when the drop_down_scroll_container index 1 is hovered -->
    <div id="sports_subcategories" class="dropdown-subcategory">
       <span data-code="SPRT01" data-image="" data-price="34.00">Sports 01</span>
       <span data-code="SPRT02" data-image="" data-price="35.00">Sports 02</span>
       <span data-code="SPRT03" data-image="" data-price="36.00">Sports 03</span>
    </div>

    <!-- THIS DIV IS AT INDEX 2 of: #dropdown.dropdown-subcategory  -->
    <!-- Will fade in when the drop_down_scroll_container index 2 is hovered -->
    <div id="colleges_subcategories" class="dropdown-subcategory">
       <span data-code="COLL01" data-image="" data-price="37.00">Colleges 01</span>
       <span data-code="COLL02" data-image="" data-price="38.00">Colleges 02</span>
       <span data-code="COLL03" data-image="" data-price="39.00">Colleges 03</span>
    </div>

</div>

      

If none of this makes sense, here's another way to look at it:

When the first element .drop_down_scroll_container

hovers, jQuery looks for the first instance .dropdown-subcategory

below it. When the second element is .drop_down_scroll_container

hovered, jQuery will open the second instance, .dropdown-subcategory

and so on. This allows you to create as many parameters as possible without having to worry about giving all the specific names, in which case only the order matters. Therefore, when the Environment parameter (whose index is 0

) is stuck, it is displayed .dropdown-subcategory

with the index 0

. This is the main idea.

So now for jQuery putting it all together:

$(document).ready(function(){

    // When the header for the custom drop-down is clicked
    $(".selectHeader").click(function() {

        // cache the actual dropdown scroll container
        var dropdown = $(this).parent().find(".drop_down_scroll_container");

        // Toggle the visibility on click
        if (dropdown.is(":visible")) {
            dropdown.slideUp();
            $(this).parent().find(".dropdown-subcategory").fadeOut();
        } else {
            dropdown.slideDown();
        }

    });

    // When a top-level menu item is hovered, decide if its
    // coorespnding submenu should be visible or hidden
    $(".drop_down_scroll_container span").hover(

        // hover on
        function() {

            // Remove the "highlighted class from all other options
            $(this).parent().find("span").removeClass("highlighted").removeClass("selected");
            $(this).addClass("highlighted").addClass("selected");

            // Get the index of the hovered span
            var index = $(this).index();

            // Use the hovered index to reveal the 
            // dropdown-subcategory of the same index
            var subcategorydiv = $(this).parent().parent().find(".dropdown-subcategory").eq(index);
            hideallSubmenusExceptMenuAtIndex($(this).parent().parent(), index);
            subcategorydiv.slideDown();
        },

        // hover off
        function() {
            if (!$(this).hasClass("highlighted")) {
                var index = $(this).index();
                var subcategorydiv = $(this).parent().parent().find(".dropdown-subcategory").eq(index);
                subcategorydiv.slideUp();
            }
    });

    // Hide all submenu items except for the submenu item at _index
    // This will hide any of the previously opened submenu items
    function hideallSubmenusExceptMenuAtIndex(formElement, _index) {
        formElement.find(".dropdown-subcategory").each(
            function(index) {
                if (_index != index) {
                    $(this).hide();
                }
            }
        );
    }

    // When any menu item is hovered
    $("span").hover(
        function() {
            $(".hoveredOver").text($(this).text());
        },
        function() {
            $(".hoveredOver").text("");
        }
    );


    // When a sub-menu option is clicked
    $(".dropdown-subcategory span").click(function() {
        $(".dropdown-subcategory span").removeClass("selected");
        $(".clickedOption").text($(this).text());
        $(this).addClass("selected");
        $(this).parent().parent().find(".selectHeader").text($(this).text());
        closeDropDown($(this).parent().parent());
        showSpecialPlateModal($(this).text(), $(this).attr("data-image"), $(this).attr("data-price"), $(this).attr("data-code"));
    });

    // Close the dropdowns contained in divToSearch
    function closeDropDown(divToSearch) {
        divToSearch.find(".drop_down_scroll_container").fadeOut();
        divToSearch.find(".dropdown-subcategory").fadeOut();
    };

    // Populate and Launch the bootstrap Modal Dialog Specialty Plates 
    function showSpecialPlateModal(name, image, price, code) {
      $('#modal_special').find('.modal-body')
        .html('<h2>' + name + '</h2>')
        .append('<br/>Special Plate Code: <span class="code">' + code + '</span><br/>')
        .append('<p>Image will go here:</p><br/><img alt="" src="' + image + '"/>')
        .append('<br/><br/>Price: <span class="price">' + price + '</span><br/>')
        .end().modal('show');
    }

    // When the modal "Accept" button is pressed
    $('.accept').on('click', function() {
        var modal_element = $('#modal_special');
        var name = modal_element.find("h2").text();
        var price = modal_element.find("span.price").text();
        var code = modal_element.find("span.code").text();
        $('#modal_special').modal('hide').end(alert(name + " was selected for a price of " + price));
    });

});

      


Note. There may already be some open source solutions out there that will take care of this issue more elegantly. But that was my approach to solving such a problem. As you can see, it takes a little tweak to get set up. You can easily control the style of the dropdown in css and you can extend it to do whatever you want.

Again, you can browse the jsfiddle to see all this code here.

Hope this helps!

+3


source


I'm not sure if this is exactly what you were looking for, but you can try something like this:



    <select name="SPECIAL" id="SPECIAL">
      <option>Please Select</div>
        <optgroup label="Environmental">
          <option 
            data-img="/images/img/AnimalFriend.png" 
            value="1">AnimalFriend</option>
          <option 
            data-img="/images/img/Aquaculture.png" 
            value="2">Aquaculture</option>
        </optgroup>
        <optgroup label="Sports">
          <option 
            data-img="/images/img/ProtectOurOceans.png" 
            value="3">Protect Our Oceans</option>
          <option 
            data-img="/images/img/ConserveWildlife.png" 
            value="4">Conserve Wildlife</option>
        </optgroup>
       </select>
      

Run codeHide result


+2


source







All Articles