Menu Widget

1 minute read

I was trying to make my own menu widget using jQuery and  I came with this below Widget.

[sourcecode language="javascript"]

//Menu Widget created by Rupesh
(function ($) {

    JDQMenu = {

        options: {

          items: { "Reports":[{

                      "File" : { "Report1":"#","Report2":"#","Report3":"#" }

                      ,"Edit" : { "Report4":"#",  "Report5":"#" }

                      ,"Report" : { "Report6":"#",  "Report7":"#" }

                      ,"Help" : {"How to see Reports":"#"}

                  }]

                  ,"Clients" : [{

                      "Search" : { "Client1":"#","Client2":"#","v3":"#" }

                      ,"Edit" : { "Client4":"#",  "Client5":"#" }

                      ,"Help" : {"How to see Clients":"#"}

                  }]

                  ,"Tools" : [{

                      "View": { "Tool1":"#","Tool2":"#","Tool3":"#"}

                       ,"Help" : {"How to find Tools":"#"}

                  }]

            }

            ,selected_menu : "Reports"

        }

        ,_init : function ( ) {

           this._create_menu( );

        }

        ,_create_menu : function ( ) {

           var that= this,el = that.element,itms=that.options.items,sel=$.trim(that.options.selected_menu);

           if( sel !="default") {

           //save element in widget cache

            var data = $(this).data(sel);

                //refresh the menu

                el.empty();

                //take element from inner widget cache data

                if(data) {

                    el.append(data);

                } else {

                    if( itms[sel] ) {

                        var menu_itms = itms[sel][0];

                        $.each(menu_itms , function ( i,v ) {

                            el.append( $("
<li>").append( $("<a>",{"class":"menu_trigger", "href":"#","text":i}) ).append("") );</a></li>
                            $.each(v,function(n,k){

                                el.find("ul#"+i+"").append($("<a>",{"href":k,"text":n}));</a>

                            })

                        })

                       $(this).data(sel,el.find("li"));

                   }

                }

                //Show the menu by triggering it

                $("a.menu_trigger").first().trigger("mousedown");

           }

        }

        ,show_menu : function (el) {

            el  = el.replace("#",'');

            this.options.selected_menu = el;

            this._create_menu( );

        }

    };

    $.widget("ui.JDQMenu", JDQMenu);    

})( jQuery );

[/sourcecode]
Now for using this widget you just have to add one ul element and call our JDQMenu widget's.
[sourcecode language="javascript"]
<ul id="menu">
</ul>
<script type="text/javascript?
$("#menu").JDQMenu();
</script>
[/sourcecode]

Comments