Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using jquery to dynamically create div

Tags:

jquery

I am trying to add a background image to a dynamically generated div. When I add the CSS property for the background, like below, it breaks my plugin:

$("<div>", {
    'class': "iviewer_image_mask",
    css: "background: url('http://somesite.com/path/to/image.jpg');"
}).appendTo(this.container);

Anybody know what I am doing wrong to add the background image?

like image 746
thindery Avatar asked Jul 31 '12 21:07

thindery


2 Answers

Of course you can add it only using string but I prefer this way because it's much more readable and cleaner.

$("<div>", {
    'class': "iviewer_image_mask",
    css: {
        "background": "url('http://somesite.com/path/to/image.jpg')"
    }
}).appendTo(this.container);

demo

like image 133
Ricardo Alvaro Lohmann Avatar answered Sep 25 '22 01:09

Ricardo Alvaro Lohmann


According to some benchmarking reported in this SO question, I believe the most efficient way to create your HTML element using jQuery would be this:

$('<div class="iviewer_image_mask" style="background: url(http://somesite.com/path/to/image.jpg);"></div>').appendTo(this.container);

Or for some extra readability:

var elm = '<div class="iviewer_image_mask" ' +
          'style="background: url(http://somesite.com/path/to/image.jpg);">'+
          '</div>';
$(elm).appendTo(this.container);
like image 21
Christofer Eliasson Avatar answered Sep 26 '22 01:09

Christofer Eliasson