peter sprang
peter sprang

Reputation: 5

Using data attributes to change background image of element.

I try to change the background image of an element with a jQuery function. Got it working with a Select element but get stucked with radio buttons.

Thanks for any help!

Works with a select box

<div id="imagechange"></div>

    <select class="logo">
    <option data-image="url(http://stackoverflow.com/image1)">image1</option>
    <option data-image="url(http://stackoverflow.com/image2)">image2</option>
    <option data-image="url(http://stackoverflow.com/image3)">image3</option>
    </select>


    <script>
    $('.logo').on('change', function () {
    $("#logo").css("background-image", ($('option:selected', this).data("image")));
    });
    </script>  

Does not work with radio buttons

<div id="imagechange"></div>

<input name="test" class="swatch" type="radio" data-image="url(http://stackoverflow.com/image1)">image1<br>
<input name="test" class="swatch" type="radio" data-image="url(http://stackoverflow.com/image2)">image2<br>
<input name="test" class="swatch" type="radio" data-image="url(http://stackoverflow.com/image3)">image3<br>


<script>
$('.swatch').on('change', function () {
$("#imagechange").css("background-image", ($('.swatch:checked', this).data("image")));
});
</script>  

Upvotes: 0

Views: 558

Answers (2)

charlietfl
charlietfl

Reputation: 171679

The problem is using context argument incorrectly.

$('.swatch:checked', this) is the equivalent of $(this).find('.swatch:checked').

However since this is a swatch there are no descendents to be found inside a radio and your selector is failing to return any matches.

Personally I would suggest always using find() instead of context argument as it is easier to read. There is no performance benefit using the context argument as it will use find() internally anyway.

Also, change() event for radios only fires on a checked radio, so you should be able to do:

$('.swatch').on('change', function () {
   $("#imagechange").css("background-image",$(this).data("image"));
});

Upvotes: 1

imnancysun
imnancysun

Reputation: 632

try without "this" in your function.

$("#imagechange").css("background-image", ($('.swatch:checked').data("image")));

Upvotes: 0

Related Questions