How do I include the css style background-image:url('') in a jquery string. This string breaks at the url('
var img=field.img;
$(".wrapper").append("<div class='slide bgimage' style='background-image: url('img/" + img + ".jpg');'></div>");
How do I include the css style background-image:url('') in a jquery string. This string breaks at the url('
var img=field.img;
$(".wrapper").append("<div class='slide bgimage' style='background-image: url('img/" + img + ".jpg');'></div>");
The string breaks because the opening single quotation mark after [style=] ends at [url(]. Since the string already contains both single quotation marks aswell as double quotation marks, you have to escape the 3rd.
Change
You should change the code from
$(".wrapper").append("<div class='slide bgimage' style='background-image: url('img/" + img + ".jpg');'></div>");
to
$(".wrapper").append("<div class='slide bgimage' style='background-image: url(\"img/" + img + ".jpg\");'></div>");
Example
var field = {
img: "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fa/140626_Tierser_Alpl_Rossz%C3%A4hne.jpg/245px-140626_Tierser_Alpl_Rossz%C3%A4hne"
}
var img=field.img;
$(".wrapper").append("<div class='slide bgimage' style='background-image: url(\"" + img + ".jpg\");'></div>");
.slide {display:inline-block;width:400px;height:400px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="wrapper"></div>
You can utilize jQuery(html, attributes)
. Note, quotes are not necessary for URL within css
url()
function.
$(function() {
var field = {
img: "http://placehold.it/100x100"
}
var img = field.img;
var div = $("<div></div>", {
"class": "slide bgimage",
"style": "background-image: url(" + img + ")"
});
$(".wrapper").append(div);
});
.wrapper,
.wrapper div {
width: 100px;
height: 100px;
display: block;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<div class="wrapper"></div>
Its not a good practice to insert/append a div element like that you might consider changing into this format
var img=field.img;
var imgUrl='img/' + img +'.jpg';
var divElement=jQuery("<div>");
divElement.addClass('slide');
divElement.addClass('bgimage');
divElement.css('background-image',imgUrl);
$(".wrapper").append(divElement);
Hope it helps