user4175297 user4175297 - 1 month ago 10
Javascript Question

Include background-image url css in jquery string

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>");

Answer

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>

Comments