OverBakedToast
OverBakedToast

Reputation: 147

Set an image background according to a data field in the div using JavaScript

I'm trying to set the background image of a bunch of divs that all have the same class name. But I want each div to have a different background image. Here is what I came up with:

HTML:

<div class="element-item" data-img="imageName.svg">
    <h3 class="name">Name</h3>
    <p class="symbol">&</p>
    <p class="number">#</p>
</div>

JavaScript:

$(document).ready(function(){
// DOM is ready here

    $("div.element-item").each(function(){

        $(this).css({"background-image", "url("+"/path/[data-img]"+")"});

    });
});

$(this).css({"background-image"**, "url("+"/fabric/images/[data-img]"+")"});**

Error:

Error: Uncaught SyntaxError: Unexpected token , on

Upvotes: 1

Views: 188

Answers (3)

bhansa
bhansa

Reputation: 7504

Use .data() to access your data-img attribute.

You cannot add the data attribute using [data-img] in your string concatenation. Use the .data("img") method to fetch the data-img attribute value and add to the string.

$(document).ready(function(){
// DOM is ready here

$("div.element-item").each(function(){
    var dataImage = '/path/' + $(this).data('img');
    $(this).css("background-image", "url(" + dataImage + ")");

});

Upvotes: 0

DraganAscii
DraganAscii

Reputation: 322

Here is a good way to start using the .attr function

$(document).ready(function(){
     $("div.element-item").each(function(){
            var $dataImage=$(this).attr("data-img");  //notice the .attr function
            $(this).css("background-image", "url('/path/" + $dataImage + "')");

      });
 });

Upvotes: 2

Tyler Roper
Tyler Roper

Reputation: 21672

The first issue is that you need to concatenate the data attribute. You can't include it within a string by doing [data-img] as you have.

Additionally, the jQuery css() function takes two different types of arguments: You can either do .css(property, value) or .css({property:value, property:value, ... }). You seem to have mixed these two and are passing it an object where it's {property,value} instead.

$("div.element-item").each(function(){
    var imgUrl = "/path/" + $(this).data("img");
    $(this).css("background-image", "url(" + imgUrl + ")");
});

Upvotes: 3

Related Questions