Reputation: 1194
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?
Upvotes: 19
Views: 71117
Reputation: 768
i read in this book Beginning JavaScript and CSS Development with jQuery that:
In earlier chapters, you’ve already seen examples of the addClass(), hasClass(), and removeClass() methods that jQuery uses to manipulate class names. It is considered best practice in client-side web development to avoid placing style declarations directly in your JavaScript code, and instead maintain a separation of behavior and presentation by placing styles in your CSS and manipulating the class names of elements for situations in which you require a manipulation of style. This is considered best practice for a reason: It makes the most sense. Since all of your presentation is neatly contained in CSS, and your behaviors in JavaScript, and your structure in HTML, your documents become much easier to manage, since it’s more predictable where to look to make a modification. If your styles are scattered inline in HTML, in the JavaScript, and in actual style sheets, then it becomes an order of magnitude more difficult to change the presentation of a document.
so on, use class name. for your purpose. like this:
$('<div class="iviewer_image_mask background-image"></div>').appendTo(this.container);
Upvotes: 0
Reputation: 1420
$("<div>").attr({
'class': "iviewer_image_mask",
'style': "background: url('http://somesite.com/path/to/image.jpg');"
}).appendTo("body");
If you really need to append it by attributes.
Upvotes: 9
Reputation: 26320
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);
Upvotes: 27
Reputation: 33885
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);
Upvotes: 23
Reputation: 34628
$("<div>")
.addClass('iviewer_image_mask')
.css('background', "url('http://somesite.com/path/to/image.jpg')")
.appendTo(this.container);
Upvotes: 9