Introduction
jQuery widgets is a very handy tool for building modern web UI. In this little tutorial we will build a simple yet useful dropdown panel widget.
Using the code
We will cover drop down panel and drop-down button within a div
. So we can call simply apply
the drop down panel feature like:
$("#userMenu").ddpanel();
And the div will have two classes to define
a drop-down button (ddpanel-button
)
and drop-down area (ddpanel-box
).
<div id="userMenu">
<a class="ddpanel-button">User Menu</a>
<div class="ddpanel-box">
<!--
<a href="#">Log out</a>
</div>
</div>
How it works
First of all when a widget is applied to a div
element, it looks for the button and box elements. This feature is hardcoded:
_create: function() {
var self = this, o = self.options, el = self.element;
o.objPanel = el.find('.ddpanel-box');
o.objButon = el.find('.ddpanel-link');
o.objPanel.hide();
var position = o.objButon.position();
var bh = o.objButon.height();
o.objPanel.css({
position: 'absolute',
left: position.left,
top: position.top + bh
});
o.objButon.click(function(){
o.objPanel.slideDown(o.effect);
});
$(document).mouseup(function (e){
o.objPanel.hide();
});
}
The _create
function is called automatically by the jQuery widget factory when a widget
is applied to an element. So we put out the initialization logic here.
Also the widget factory gives the element widget applied as:
el = self.element;
Also we define an options
variable to store widget-specific data such as settings.
options: {
objPanel: '',
objButon: '',
effect: 'fast'
}
You may name the options
variable whatever you want but options
is a special variable name recognized by
the widget factory class.
This enables to set options for the widget easily.
$('#userMenu').ddpanel({
effect:'slow'
});
As you can see, the parameter you give the widget create function is recognized as options
.
Now, we show our drop down panel when the user clicks the drop down button and hide
the panel when the user clicks anywhere on the document.
But in case we don't want the panel to be hidden when the user clicks on the panel. In this case, we need to modify
the hide-logic something like:
$(document).mouseup(function (e){
if (o.objPanel.has(e.target).length === 0){
o.objPanel.hide();
}
});
This time we check if the clicked area is not in the panel div. Have fun!