I'm making a plugin that makes a dropdown on an element and use a pre-defined element as the dropdown menu outside the applied element.
The markup looks like this
<a href="javascript:void(0)" id="some-menu" data-dropdown="dropdown-element">Click</a>
<ul id="dropdown-element">
<li><a href="#">First item</a></li>
<li><a href="#">Second item</a></li>
</ul>
And using $("#some-menu").dropdown({ placement: 'top' });
will turn #dropdown-element
to a dropdown. All good and dandy.
placement
decides on how the dropdown is positioned according to the element (top, bottom, right, left) but this should be fairly easy to apply, when I have figured the default positioning out.
I tried using this code from Bootstrap's Tooltip plugin
pos = getPosition($element, inside);
actualWidth = $this[0].offsetWidth;
actualHeight = $this[0].offsetHeight;
switch (inside ? placement.split(' ')[1] : placement) {
case 'bottom':
tp = {top: pos.top + pos.height, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 'top':
tp = {top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2};
break;
case 'left':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth};
break;
case 'right':
tp = {top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width};
break;
}
But without luck.
This is what it looks like
And this is the wanted result
I want it horizontally centered to #some-menu
and the dropdown to be applied to any element, inlines too and keep both the vertical and horizontal positioning.
Edit:
I found out that the dropdown was created inside a element with position: relative
, which is why its offset is wrong. My question is now what the best way to move the element into the body (or perhaps a better solution for this) and keep good performance without touching the DOM more than needed.