holyredbeard
holyredbeard

Reputation: 21178

Dynamically create divs with height and width

I'm dynamically creating divs in my application, and wants through parameters in a function to choose the width and height of the divs. The code below works, however I don't want to add styling directly to my HTML document which it does.

Is there another way to accomplish this without adding css to the HTML document?

function createDiv(theWidth, theHeight){

var box = $('<div/>', {
   'class': 'box',
   'width': theWidth,
   'height': theHeight,
}).appendTo('#content');

}

Note: The height and width is retrieved from a JSON-file through AJAX and can differ. By that reason I can't create different classes with different heights and widths.

Upvotes: 0

Views: 2227

Answers (3)

epignosisx
epignosisx

Reputation: 6192

The only other way I can see this happening is by returning in your JSON result a style element with some auto-generated class containing the new width and height. You will add the style to your document and then add the class to the element. Here is a sample:

$(function(){
    var json = {
        cssClass: "random1",
        style: "<style type='text/css'>.random1{width:200px;height:200px}</style>"};

    alert("Wait");
    $("head").append(json.style);
    $("div").addClass(json.cssClass);
});

For a working example: http://jsfiddle.net/epignosisx/YNpFV/

Upvotes: 0

Richard
Richard

Reputation: 4415

You can either:

  • Add a predefined class to the div, or
  • Add a style attribute with the contents

Why "I don't want to add styling"??

Edit:

function createDiv(theWidth, theHeight){

    $('<div class=\'box\' style=\'width:'+theWidth+'px;height:'+theHeight+'px;\'/>').appendTo('#content');

}

Upvotes: 2

Michael Berkowski
Michael Berkowski

Reputation: 270599

You would need to define the height and width in a CSS file, and add the appropriate class to your new element.

.box {
  height: ...;
  width: ...;
}

var box = $('<div/>', {
    class: 'box'
}).appendTo('#content');

Or

var box = $("<div/>").addClass("box").appendTo("$content");

Upvotes: 0

Related Questions