Dushyant Patel’s Blog

Position DIV to element using jQuery

Requirement is how to position DIV to some element on the fly using jQuery?

Using jQuery position(), can access position of element and assign position to DIV on the fly.

For Example: onClick of link element access the position of <a> element and on the base of that assign position to DIV.

HTML Code:

<div>
   <a href="#" id="pospayerlnk">Position Layer</a>
   <div id="testDiv">
         Test
   </div>
</div>

CSS Code:

body {
   font-family:Verdana, Arial, Helvetica, sans-serif;
   font-size:11px;
}

.center-main {
   width:400px;
   margin:auto;
   margin-top:100px;
}

#testDiv {
   width:100px;
   height:100px;
   position:absolute;
   top:10px;
   left:10px;
   background-color:#CCCCCC;
   border:1px solid #666666;
}

a#pospayerlnk {
   border:1px solid #3366CC;
   height:18px;
   display:block;
   width:100px;
   color:#0066CC;
   line-height:18px;
   text-decoration:none;
   text-align:center;
}
</style>

jQuery Code:

<script type="text/javascript" src="jquery-1.3.2.js"></script>
<script type="text/javascript">
$(document).ready(function () { $("a#pospayerlnk").click(function () { var position = $(this).position(); $("div#testDiv").css("left", position.left); $("div#testDiv").css("top", position.top+20); }); }); </script>
Advertisements

Filed under: Technology

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: