1

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')+"')");
1
  • jQuery will take all data-* attributes and add them to the data for the elements. This means that you can access the data-image attribute via $(selector).data("image") (not img) Commented Apr 22, 2016 at 15:25

1 Answer 1

3

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>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.