Dynamic Positioning with jQuery
I have been working on a few sprints lately that require some javascript to do dynamic positioning of a DOM element on whatever was just clicked on the screen. Here is a sample of some of that code.
It assumes that there is an element, a.some_link, that when you click it the dynamically positioned element, #DP, places itself just to the right and centered vertically. It will also detect if positioning to the right will cause it to be off the screen and flip it to the left side instead. The only CSS requirement is that #DP be "position: absolute;".
[js]$("a.some_link").click(function() {
//Get the coordinates of the clicked element.
var cellPosition = $(this).position();
//Add the left displacement to the width of the trigger,
//placing the DP just to the right of it.
var horizontalPosition = cellPosition.left + $(this).outerWidth();
//Here is the fancy part. If the position plus the width of your DP
//if greater than the window width, change the position to the left
//side of the trigger.
if (horizontalPosition + $("#DP").outerWidth() > $(window).width()) {
horizontalPosition = cellPosition.left - $("#DP").outerWidth();
}
//Center your DP vertically on the trigger.
var verticalPosition = cellPosition.top - ($("#DP").outerHeight() / 2) + ($(this).outerHeight() / 2);
//Update the position of your DP.
$("#DP").css({top: verticalPosition, left: horizontalPosition});
});[/js]
Also note that if you were to call "animate" instead of "css" in that last call, then it would animate the movement instead of just snapping it to the new position.