CroVG
CroVG

Reputation: 149

Jquery positioning with position()

I want to make something like this:

enter image description here

So when I click on text "Hi, ..." it toggle(); dropdown menu and positions that menu like on image.

But when I resize browser I get something like this:

Here is jsfiddle enter image description here

Upvotes: 1

Views: 46

Answers (1)

Lauromine
Lauromine

Reputation: 1493

Put your code :

var x = $(".icons").position();                     
document.getElementById("user_menu").style.left = x.left + "px";

Inside $(".icons").click(function(){

It will recalculate the position each time you click to open the dropdown.

Edit :

You can also bind the position to the window.onresize event :

$(".icons").click(function(){
    $("#user_menu").toggle();
    calculatePosition();
});

$(window).resize(calculatePosition);

function calculatePosition() {
    var x = $(".icons").position();                     
    document.getElementById("user_menu").style.left = x.left + "px";
}

Thanks to the code above, your element will be repositionned when you resize the window (avoid the offset when the dropdown is opened)

Upvotes: 4

Related Questions