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
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
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.