Chris Pilie
Chris Pilie

Reputation: 451

Escaping double quotes in a style string in jQuery

I have a jQuery div as follows:

<div class="col-xs-8 col-xs-offset-2 col-sm-offset-0 col-sm-6 bg-image"
     style="background-image: url('images/page-1_img09.jpg')" data-equal-group="1">
</div>

What I would like to be able to do is create a dynamic image variable within a function and escape the quotes similar to this:

// some code      
      var html  = "";
      var photo = data[i].photo;
        html += "<div class='col-xs-8 col-xs-offset-2 col-sm-offset-0 col-sm-6 bg-image pull-sm-right pull-lg-left' style='background-image: url('";
        html += photo; 
        html += "')' data-equal-group='1'></div>";

The problem that I am having is that the double quotes around the image.jpg are not loading into the browser. Instead this is what I get:

background-image: url(images/demsoc.jpg)

Is there another way of doing this which would include the single quotes?

Upvotes: 1

Views: 632

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206121

Format properly the quotes like:

var html = "<div class='classes' style=\"background-image: url('" + data[i].photo +"')\" data-equal-group='1'>test</div>";
//                                      ^---- Has to be Double-Q. so escape them ------^

to recap: url address should be in single quotes, therefore the style="" quotes has to be double quotes. Since you already use double quotes to delimit your JS String, those have to be escaped style=\" blabla \".

jsBin demo

Result from Developer Tools Elements Console:

<div class="classes" style="background-image: url('//placehold.it/300x300')" data-equal-group="1">test</div>

Upvotes: 1

Related Questions