Getting jQuery.height () after adding to another div returns 0

I am trying to create a div that scrolls only when it is above a certain height after adding text to it. I check the height with jquery and returns zero every time. Any suggestions?

HelpOverlay.prototype.buildContent = function(helpMappings){
this.content = $('<div class="content"></div>');
var table = $('<table></table>');
table.append($('<tr><td class="key"><h3>Key</h3></td><td class="command"><h3>Command</h3></td></tr>'));
this.content.append(table);
for (var whichCategory = 0; whichCategory < helpMappings.categories.length; whichCategory++) {
    var category = helpMappings.categories[whichCategory];
    var categoryDiv = $('<div class="category">' + category.category + '</div>');
    this.content.append(categoryDiv);
    var categoryTable = $('<table></table>');
    for (var whichMapping = 0; whichMapping < category.mappings.length; whichMapping++) {
        var mappings = category.mappings[whichMapping];
        var row = $('<tr></tr>');
        var keyCell = $('<td class="key">' + mappings.key + '</td>');
        var commandCell = $('<td class="command">' + mappings.command + '</td>');
        row.append(keyCell);
        row.append(commandCell);
        categoryTable.append(row);

    }
    this.content.append(categoryTable);
}

this.helpOverlay.append(this.content);
console.log(this.content.height());
}

console.log (this.content.height ()) returns zero.

+3
source share
2 answers

In relation to this line:

this.helpOverlay.append(this.content);

Is it this.helpOverlayalready part of the DOM? Any element that is not inserted in the DOM will return 0 in height and width until it is inserted.

Edit:

this.content.css( 'display', 'none' ).appendTo( 'body' );
var dims = { 'height': this.content.height( ),
             'width':  this.content.width( ) };
this.content.detach( );
+3
source

As a side note, you don't need to wrap the element creation in $ () if you pass it to another jQuery method. This is your code above ...

table.append($('<tr><td class="key"><h3>Key</h3></td><td class="command"><h3>Command</h3></td></tr>'));

( ) , , , 1 $()...

table.append('<tr><td class="key"><h3>Key</h3></td><td class="command"><h3>Command</h3></td></tr>);
0

All Articles