Reputation: 35
I would like to change the background image url within the parent row when the selected color is select. When click on the first col pink, the first col background image will change to pink and for the second col click on white, the second col will change to white without affect the first col.
jQuery(document).ready(function ($) {
$(".selector a").change(function(){
if ('.image-black').hasClass('selected'){
$(".image").css("background-image", "url(https://cottontee.co/wp-content/uploads/2018/10/black.jpg)");
} else {
if ('.image-white').hasClass('selected'){
$(".image").css("background-image", "url(https://cottontee.co/wp-content/uploads/2018/10/white.jpg)");
} else {
if ('.image--pink').hasClass('selected'){
$(".image").css("background-image", "url(https://cottontee.co/wp-content/uploads/2018/10/pink.jpg)");
}
}
}
});
});
.image {
width: 500px;
height: 500px;
background-size: cover;
}
<div class="row">
<div class="col">
<div class="image" style="background-image: url(https://cottontee.co/wp-content/uploads/2018/10/white.jpg);"></div>
<div class="selector">
<a href="#" class="image-black selected">Black</a>
<a href="#" class="image-white">White</a>
<a href="#" class="image-pink">Pink</a>
</div>
</div>
<div class="col">
<div class="image" style="background-image: url(https://cottontee.co/wp-content/uploads/2018/10/white.jpg);"></div>
<div class="selector">
<a href="#" class="image-black selected">Black</a>
<a href="#" class="image-white">White</a>
<a href="#" class="image-pink">Pink</a>
</div>
</div>
</div>
https://jsfiddle.net/1so3mwbr/
Upvotes: 0
Views: 76
Reputation: 452
Please try below code
jQuery(document).ready(function ($) {
$(".selector a").click(function(){
$(".selector a").removeClass('selected');
$(this).addClass('selected');
var className = $(this).attr('class').split('-')[1].split(' ')[0];
$(".image").css("background-image", "url(https://cottontee.co/wp-content/uploads/2018/10/"+className+".jpg)");
});
});
Upvotes: 1