-1

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.

SenTaiyou
  • 129
  • 2
  • 10
  • Please post the relevant HTML and Javascript code. – David May 27 '14 at 10:01
  • Fiddle please. http://jsfiddle.net – Abdennour TOUMI May 27 '14 at 10:02
  • As far as i know, `ready()` is triggered after all elements are loaded... – T J May 27 '14 at 10:04
  • have you tried `$(window).on('load', function() {})`, if that doesn't work try the solution [in this](http://stackoverflow.com/questions/3877027/jquery-callback-on-image-load-even-when-the-image-is-cached) - I usually do a counter for the images loaded and when the counter matches my imgs.length I'll fire a function – Pete May 27 '14 at 10:07
  • @Pete I have tried $(window).on('load', function() {}) as well, for somereason when I do .load, the event doesn't get fired at all. – SenTaiyou May 27 '14 at 11:05
  • your x variable is set wrong `$("Mon")` is not valid and you can try running the script on `$('#appointment_table').load` (within your document ready function) – Pete May 27 '14 at 11:09
  • @Pete sorry I made a typo in the post should be $('#Mon') also I've just tried your second suggestion and I'm finding when ever i use .load() that event is never fired when I run it :S – SenTaiyou May 27 '14 at 11:15

5 Answers5

0

I think you need to use offset(), as position() is relative to the parent element:

x = $('#div1').offset().left + 100;
y = $('#div1').offset().top;

Example fiddle

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
0

I think, you misused the appendTo()-function.

Try this:

$('#container').append('<div></div>').css({
    'position': 'absolute', 
    'top': y, 
    'left': x
});
tjati
  • 5,761
  • 4
  • 41
  • 56
0

Your code is just fine. The problem seems to be at two places:

  1. Perhaps your #container div is not relatively positioned.
  2. You are saying: "... should put the new <div> element 100px to the right of #div1. ...", but your code is $('#div1').position().left + 100: which means it is not 100px to the right, but is 100px from the left.

Demo: http://jsfiddle.net/abhitalks/q86HM/

#container {
    background-color: #ccc;
    width: 400px; height: 400px;
    position: relative;
}

#div1 {
    background-color: yellow;
    width: 200px; height: 200px;
    position: absolute;    
    top: 10px; left: 10px;
}

x = $('#div1').position().left + 100;
y = $('#div1').position().top;

$('<div>').appendTo('#container').css({'position': 'absolute', 'top': y, 'left': x, 'width': '100px', 'height': '100px'});

It seems to be working just fine.

Abhitalks
  • 27,721
  • 5
  • 58
  • 81
  • Thanks for the reply. The issue I'm having is nothing to do with the actual appending of the new div to the page, it is with trying to get the top and left positions of the existing div from within the .ready() event. At this stage for some reason the positions are 0. – SenTaiyou May 27 '14 at 10:27
  • so if I have: $(document).ready(function(){ console.log($('#div1').position().top); console.log($('#div1').position().left); }); they both return 0, but if I do the same thing from a button click event after the page has fully loaded it returns the correct values. – SenTaiyou May 27 '14 at 10:28
  • @SenTaiyou: Did you see the fiddle I linked to? It is perfectly getting the top/left of the existing div. `.ready` is the right place. – Abhitalks May 27 '14 at 10:29
  • @SenTaiyou: Now see this: (http://jsfiddle.net/abhitalks/q86HM/1/) It IS getting the top/left correctly. Did you fix the positioning correctly? – Abhitalks May 27 '14 at 10:31
  • I've reviewed the fiddles and tried the relative position on the container etc but still don't get the values I need....I will amend my post to include my original html and script – SenTaiyou May 27 '14 at 10:37
0

Use this event:

$(document).load(function () {
 // code here
});
Abhroo
  • 126
  • 8
-1

I'd advise putting you function in small timeout, so all element will have time to render (probably, you render first div with jquery, so you element has no position on document ready) And dont forget to close div!

  setTimeout(function(){

     $('<div></div>').appendTo('#container').css({
        'position': 'absolute', 
        'top': y, 
        'left': x
     });

  },1)
Prosto Trader
  • 3,471
  • 3
  • 31
  • 52