Jony S
Jony S

Reputation: 159

How to set DIV background-image css jquery?

Motto is to set/update(ajaxified) a DIV background image.

        $.getJSON("https://itunes.apple.com/search?term=" + searchTerm + '&limit=1' + '&callback=?', 
        function(data) {
        $.each(data.results, function() {
        var art = this.artworkUrl100;
        $('.photo').parent().css('background-image', 'url(' + art + ')');
      }
    }

On HTML i've this:

<div id="results" class="photo"></div>

Upvotes: 0

Views: 108

Answers (1)

Carlton
Carlton

Reputation: 838

You are setting the background image to a parent element instead of the .photo div.

Try this:

$.getJSON("https://itunes.apple.com/search?term=" + searchTerm + '&limit=1' + '&callback=?', 
    function(data) {
        $.each(data.results, function() {
            var art = this.artworkUrl100;
            $('.photo').css('background-image', 'url(' + art + ')');
        })
});

If multiple data.results are returned then only the last be used for the background image due to the $.each loop that you are using. If you are maintaining the limit=1 on the JSON call then this won't be a problem.

Upvotes: 2

Related Questions