I am dynamically creating <div>
elements to add to the page once the page has been loaded, where the positions for these are dependent on the positions of other elements on the page.
eg.
x = $('#div1').position().left + 100;
y = $('#div1').position().top;
$('<div>').appendTo('#container').css({
'position': 'absolute',
'top': y,
'left': x
});
Which should put the new <div>
element 100px to the right of '#div1'.
The problem I am having is that in the $(document).ready
event, the x
and y
values are 100
and 0
respectively, i.e. the $('#div1').position()
is returning 0
values, which I have verified by checking it on the console. Alternatively, when i put the same checks for x
and y
values on a button click event instead, i.e. after everything has finished loaded fully, it returns the correct x
and y
values that I am expecting. Which means when I am calling the function in the document.ready
event, all the elements have not yet loaded on the page.
I have tried using window.load as well as trying to put it in ('#div1').ready
/ .load
as well and neither of them work.
Is there any other event that would allow me to call the function automatically when the page loads rather than having to wait for the user to click a button?
<div id="container">
<table id="appointment_table">
<tr>
<th></th>
<th id="Sun">Sunday </th>
<th id="Mon">Monday </th>
<th id="Tue">Tuesday </th>
<th id="Wed">Wednesday</th>
<th id="Thu">Thursday </th>
<th id="Fri">Friday </th>
<th id="Sat">Saturday </th>
</tr>
@for(var i=6; i < 21; i++)
{
<tr id="@i">
<td class="active">@i:00</td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
}
</table>
<script type="text/javascript">
$(document).ready(function () {
var x = $("#Mon").position().left;
var y = $("#17").position().top;
console.log(x);
console.log(y);
$("<div>")
.appendTo('#container')
.css({'width': '100px', 'left': x, 'height': '100px', 'top': y, 'position': 'absolute'});
});
This is a simplified version of the code as I am not allowed to post the full version but all the main parts are there. The idea is to create a div element for an "appointment" taken from the model data, and depending on the date on the appointment, taking the correct x value from the correct Day element, and the y value from the correct time element for the positioning of the created div so it gets put directly on the background table.