Reputation: 5526
I am sure this question may have been asked, but I couldn't find the right solution..
I need to show a menu on mouse over of an icon which can be placed anywhere on the page. Example code is here: ( http://jsfiddle.net/Qfjdk/2/ ) This shows the popup, however if I change the code from
#nav {
margin:0;
padding:0;
list-style:none;
float: left;
}
to
#nav {
margin:0;
padding:300px;
list-style:none;
float: right;
}
As can be seen, the position of the menu is always centered below. I want to change the position of the menu based on where the icon is displayed.
If the icon element is aligned right, I want to position the menu to start on right edge of icon. If the icon element is towards bottom left of displayed page, I want the menu bottom left to align with element top left etc..
I am not looking for the algorithm, am looking for the right way of setting parameters.. Appreciate your help
Upvotes: 3
Views: 3271
Reputation: 6961
I would first define how many alternatives you want to support (for example, 4: button on right-top, right-bottom, left-top or left-bottom), and create a set of classes with these different options (.pos1, .pos2, .pos3, .pos4).
Then I'd use JS or jQuery to calculate the offset of the icon relative to the window. Depending on that result, I would give the popup the correct class from the ones you previously created. You can do this on load as well as on window resize. For example, calculating a distance to the right and applying css changes (you could apply a class instead, but this is just to show how it'd work):
var callback = function () {
// when hover on an element, calculate offset to right
$('.yourElement').mouseover(function(){
var currentElement = $(this);
var distanceRight = $(window).width() - ($(currentElement).offset().left + $(currentElement).width());
// If the distance is less than 50, then do...
if (distanceRight < 50) {
$('.yourPopup').css("left","-200px");
}
else {}
});
};
$(document).ready(callback);
$(window).resize(callback);
Upvotes: 1