Relative position through Jquery

Posted By : Hema Chauhan | 09-Jan-2017

Through this method, we can arrange a given div element relative to the position of an existing div.
To do this, we firstly need to set the width and height of the existing element, and then use these values to position the new div element accordingly. 
The following code will add an element as a sibling to the existing element (parent) which is positioned inside the parent element (30 pixels from the top and 50 pixels from the left of the existing element is top-left corner, and with a width 20 pixels less than that of the existing element.
I've shared the HTML and CSS code below:

Write the code in HTML:-

<div style="position:absolute;left:50;top:30;">
    <ul>
        <li class="place">item1</li>
        <li class="place">item2</li>
        <li class="place">item3</li>
    <ul>
<div>
<div style="display: none;" id="menus">
   <ul>
       <li>A1</li>
       <li>A2</li>
       <li>A3</li>
    </ul>
</div>

 

Write the code in CSS:
.placeholder, #menus {
    border: 1px solid black;
    padding: 10px;
    margin: 10px;
}

 


Write the code in Jquery:
$(".place").mouseover(function() { 
    var pos = $(this).position();
    var width = $(this).outerWidth();
    $("#menus").css({
        position: "absolute",
        top: pos.top + "px",
        left: (pos.left + width) + "px"
    }).show();
});

In this blog,.position() uses the position relative to the offset parent,so it supports position: relative parent elements
.outerWidth() takes into account border and padding.show the menu directly over the place.

 

THANKS

About Author

Author Image
Hema Chauhan

Hema is a bright UI designer, having knowledge of core php, HTML, CSS. Her hobbies are interacting with people, listening to music and dancing.

Request for Proposal

Name is required

Comment is required

Sending message..