Mimmo
Mimmo

Reputation: 123

jQuery set CSS style of Class by using Data attribute

I've this elements

<div class="circle-200" data-image="pic1" ></div>
<div class="circle-200" data-image="pic2" ></div>
<div class="circle-200" data-image="pic3" ></div>

after the page is loaded i would that the data-image values became the backgound-image of corresponding circle-200 class

Is it possible, using jQuery, do such a thing ?

$('.circle-200').css('background-image', "url('"+$(this).data('img')+"')");

Upvotes: 1

Views: 1942

Answers (1)

Satpal
Satpal

Reputation: 133403

You need to use .css( propertyName, function )

A function returning the value to set. this is the current element. Receives the index position of the element in the set and the old value as arguments.

Also note it should be image not img

$('.circle-200').css('background-image', function() {
    return "url('" + $(this).data('image') + "')");
});

$('.circle-200').css('background-image', function() {
  return "url('" + $(this).data('image') + "')"
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="circle-200" data-image="pic1">pic1</div>
<div class="circle-200" data-image="pic2">pic2</div>
<div class="circle-200" data-image="pic3">pic3</div>

Upvotes: 3

Related Questions