Mongo
Mongo

Reputation: 151

Replace div background url by image src

How can I replace div background url by image src?

<img class='active' src="http://s1.iconbird.com/ico/2013/12/547/w128h1281387216564facebook3.png"/>
<div class='content-box'></div>
<div class='btn'>CLICK</div>

.content-box{
background-image: url(http://s1.iconbird.com/ico/2013/12/547/w128h1281387216591googleWhite.png);
background-repeat: no-repeat;
width: 130px;
height: 130px;
}
.btn{
position: fixed;
left: 200px;
top: 73px; 
width: 40px;
height:40px;
}

Tried it:

$(document).ready(function(){
  $('.btn').click(function(){
        var imgSrc = $('.active').attr('src');
        $('.content-box').css('background-image', 'url(imgSrc)'); 
  });
});

http://jsfiddle.net/fresa150/H2aWF/

Upvotes: 2

Views: 467

Answers (3)

Somnath Kharat
Somnath Kharat

Reputation: 3610

you need to do this:

$('.content-box').css('background-image', "url('"+imgSrc+"')"); 

jsfiddle

Upvotes: 0

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62498

You need to do :

$('.content-box').css('background-image', "url("+imgSrc+")"); 

As imgSrc is a variable it will not be recognized in double quotes so you need to concatenate variable

FIDDLE DEMO

Upvotes: 1

Satpal
Satpal

Reputation: 133453

imgSrc is a variable hence you should not use it in quotes.

Use

$('.content-box').css('background-image', 'url(' + imgSrc + ')');

DEMO

Upvotes: 6

Related Questions