tlindig / position-calculator

jQuery plugin, to calculate the position of an element relative to another element or event. Tries to find a collision free position within the viewport of a given container.
MIT License
101 stars 13 forks source link

Dropdowm auto position dynamically of window height #1

Closed Alkasih closed 10 years ago

Alkasih commented 10 years ago

I want to know if Dropdown auto position can be set dynamically.

  jQuery(function($) {
  $(document).on("shown.bs.dropdown.position-calculator", function(event, data) {
  var $item = $('.dropdown-menu', event.target);
  var target = data.relatedTarget;

// reset position
$item.css({top:0, left:0});

// calculate new position
var calculator = new $.PositionCalculator({
  item          : $item,
  target        : target,
  itemAt        : "top left",
  itemOffset    : { y:3, x:0, mirror:true },
  targetAt      : "bottom left",
  flip          : "both"
});
var posResult = calculator.calculate();

// set new position
$item.css({
  top: posResult.moveBy.y + "px",
  left: posResult.moveBy.x + "px"
});
}); 
});

Those code only changes the position of 'opening dropdown menu' to the top if the window has reached the bottom. What i want is that the dropdown will count the height of the window. For exampale: if the "y position" of dropdown button is in the 40% of window height, then the dropdown menu will open to the bottom of the button. HOWEVER, if the "y position" of dropdown button is in the 60% of window height, then the dropdown menu will open to the top, eventhough still there are enough space to open it to the bottom of the button.

Thanks for understanding my question.

tlindig commented 10 years ago

Could you please make a jsbin example?

For now I see two ways to solve.

Way A: You could create an invisible boundary element that has the requeried dimensions and give that to the position calculator as option.

Way B: Check the result of PositisonCalculator before you apply it to the dropdown. If it is to near to the window bottom, calculate a new position with .calcVariant(item_at, target_at) and apply this.

Alkasih commented 10 years ago

Hi thanks for the advance reply. Here is the Jsbin http://jsbin.com/hofen/1/edit However there is something wrong in the Jsbin because it doesn't open the menu to the top even if the window has reached the bottom position. It does in my html file. But that's not the main problem. I still want the dropdown menu will open dynamically as my question above. Thank you very much to spare your time on this question.

tlindig commented 10 years ago

In your example, you forgotten to load the position-calulator sorces.

tlindig commented 10 years ago

here is an example with Way A.

http://jsbin.com/poqekuce/1/edit

Alkasih commented 10 years ago

It's beautiful! Thanks! :)

tlindig commented 10 years ago

Given example solve the problem.