1

I have a small problem, I want to get "path" from data attribute and add to background.

HTML

<div>
  <div data-image="../images/header.jpg"></div>
</div>

jQuery

$('[data-image]').css(
    {
        background: "url("+$(this).data('image')+") no-repeat center",
        backgroundSize: "cover",
        height: ($(document).height()/ 3)
    }
);

Do you have any idea how do this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
LAron
  • 13
  • 3

1 Answers1

2

Just cache the element in a variable and use it

var elm = $('[data-image]'); // cache it
elm.css({
    background: "url("+ elm.data('image') +") no-repeat center", // use it
    backgroundSize: "cover",
    height: ($(document).height()/ 3)
});

If there are more elements, you could use each

elm.each(function(){
    $(this).css({
        background: "url("+ $(this).data('image')+ ") no-repeat center",
        backgroundSize: "cover",
        height: ($(document).height()/ 3)
    });
});
Amit Joki
  • 58,320
  • 7
  • 77
  • 95