Alexander Hein Alexander Hein - 3 months ago 19
jQuery Question

JQuery: Change background image if a radio button gets checked

How do I change the background image of a element if a radio button gets

checked


Please take a look at my example below.



$("#outside input:radio").change(function(){
$("#color-outside").css("background-image", ($('#outside input:checked').data("image")));
}).change();

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="color-outside" style="background-image: url();"></div>


<div class="swatch-element black">
<input id="black" type="radio" name="contact[Farbe Innen]" value="black" data-image="https://cdn.shopify.com/s/files/1/1329/9539/t/2/assets/schwarzblau.png?5811407930308074056" checked="checked" />
<label for="schwarz"></label>
</div>

<div class="swatch-element white">
<input id="white" type="radio" name="contact[Farbe Innen]" value="white" data-image="https://cdn.shopify.com/s/files/1/1329/9539/t/2/assets/weiss.png?5811407930308074056"/>
<label for="white"></label>
</div>




Answer

$(document).ready(function(){
 $("input:radio").change(function(){
$("#color-outside").css('background-image','url('+ $(this).data("image")+')');
});
});
#color-outside{
  width: 100vw;
  height: 100vh;
  background-size: cover;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>


<div id="color-outside"></div>


<div class="swatch-element black">
<input id="black" type="radio" name="contact[Farbe Innen]" value="black" data-image="https://cdn.shopify.com/s/files/1/1329/9539/t/2/assets/schwarzblau.png?5811407930308074056" checked="checked" /> 
<label for="schwarz"></label>
</div>

<div class="swatch-element white">
<input id="white" type="radio" name="contact[Farbe Innen]" value="white" data-image="https://cdn.shopify.com/s/files/1/1329/9539/t/2/assets/weiss.png?5811407930308074056"/> 
<label for="white"></label>
</div>

Comments