0

I'm trying to create an element on the fly and then get the center of said element. Here is what I have:

function drawnode(entity, x, y) {

    var ele = ""
    ele += "<div class='relNode'>";
    ele += "<span>" + entity.name() + "</span>"
    ele += "<div>"

    var node = $(ele).appendTo('#rPaper').get(0);
    var offset = node.offset();
    var width = node.width();
    var height = node.height();

    var centerX = offset.left + width / 2;
    var centerY = offset.top + height / 2;

    node.css("top", centerY + y).css("left", centerX + x);

}

This gives the error

Object #<HTMLDivElement> has no method 'offset'

I originally tried it without the .get(0) and it gives no errors but the height and width are both 0.

What am I doing wrong?

3 Answers3

3

You are trying to call jQuery function on DOM object as get gives you DOM object not jQuery object Use eq() instead of get() to get jQuery object

 var node = $(ele).appendTo('#rPaper').eq(0);
Adil
  • 146,340
  • 25
  • 209
  • 204
  • I don't think it is required as the `ele` has only one root element – Arun P Johny Dec 05 '13 at 04:42
  • 2
    @ScottBeeson: It works for me: http://jsfiddle.net/FZNam/. Could it be that `#rPaper` or any other descendant of `node` is not visible? Which browser are you using? – Felix Kling Dec 05 '13 at 04:47
  • Hmm, that probably is the problem. It's in a tab, but the function is called before that tab is selected. –  Dec 05 '13 at 04:48
  • @Scott: Then that's your problem. – Felix Kling Dec 05 '13 at 04:50
  • Hmm, is there an easy fix or will I have to wait until the tab is visible to draw the nodes? –  Dec 05 '13 at 04:51
  • @Scott: You could show and hide the element (http://jsfiddle.net/FZNam/2/). But that could lead to flashing content, you'd have to test if it works for you. This might work better for you: http://stackoverflow.com/q/1472303/218196. – Felix Kling Dec 05 '13 at 05:00
0

.get(index) returns a dom element reference which does not have methods like offset() which are provided by jQuery. so you need to use a jQuery wrapper for the element to use methods like .offset()/.width()

var node = $(ele).appendTo('#rPaper');
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
  • That's what I had originally, but then the height and width are 0. –  Dec 05 '13 at 04:39
  • @ScottBeeson are you sure that the element `#rPaper` exists in the dom – Arun P Johny Dec 05 '13 at 04:44
  • Yes. I can see the new element on the page when it is created. –  Dec 05 '13 at 04:44
  • @ScottBeeson can you help to recreate the problem.. in this [fiddle](http://jsfiddle.net/arunpjohny/vsjA5/1/) it seems to be working fine – Arun P Johny Dec 05 '13 at 04:48
  • Yeah, @Felix King just pointed out that the problem is probably caused by the fact that #rPaper is on a tab that isn't initially visible. –  Dec 05 '13 at 04:49
0
 var node = $(ele).appendTo('#rPaper');
 var offset = node.offset();
Ankit Tyagi
  • 2,381
  • 10
  • 19