Search code examples
javascriptjquerycssthisjquery-data

jQuery get path from data attribute


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?


Solution

  • 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)
        });
    });