Real Dreams
Real Dreams

Reputation: 18028

Positioning an element relative to another one

I want to assign xmenu-toggle class to an element that when clicked a menu appear in the left-botton side of it. I tried following, but position of menu will be changed in successive clicks. What's wrong?

    $('.xmenu-toggle').click(function (event) {
        event.stopPropagation();
        var pos=$(this).offset();
        $(this).siblings('.xmenu').offset({top:pos.top+10,left:pos.left+10}).toggle();
    }) 

Html:

<div class="xmenu-toggle">Click me!</div>
<div class="xmenu">I am the menu, I have relative position</div> 

Upvotes: 0

Views: 78

Answers (1)

DevlshOne
DevlshOne

Reputation: 8457

It looks like it has to do with the placement of the .toggle(). I moved it to before the .offset() and it came up consistently in the same spot.

 $('.xmenu-toggle').click(function (event) {
     var offset = $(this).offset();

     $(this).parent().find('.xmenu').toggle().offset({
         top: offset.top + 10,
         left: offset.left + 10
     });

 });

jsFiddle Demo

Upvotes: 1

Related Questions