What is the best way to apply a background image to a DIV element using CSS

The main aim is to change the background image of a DIV using AJAX.

        $.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 + ')');
      }
    }

This is the HTML code:

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

Answer №1

You have mistakenly applied the background image to a parent element instead of the designated .photo div.

Consider implementing this corrected code:

$.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 the JSON data returns multiple data.results, only the final result will be utilized for the background image due to the loop created by $.each. As long as you maintain the limit=1 on the JSON call, this issue should not arise.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is there a way to switch an input's appearance to resemble that of a label?

Looking to customize my input fields to resemble labels at first, then apply editable styles with angular.js upon button click. Utilizing bootstrap for my project, wondering if there is a built-in class that can be toggled on and off for these inputs? ...

How can I delete an individual HTML element that does not have a class or ID?

I am currently working with a theme that cannot be altered due to automatic update requirements. The theme includes the following HTML code snippet: <div class="dropdown-menu"> <a href="#">Profile</a> | <a href="#">Logout</a> ...

Combining various array values into a single key in JSON格式

Issue: I am working on a sign-up form for new users using HTML. The goal is to store multiple arrays (each containing "username: username, password: password, topScore: 0) within one JSON key ("user" key). However, the current functionality only allows f ...

The XMLHttpRequest() function throws NS_ERROR_FAILURE when sending requests to localhost using either an absolute or relative path

Encountering an error in Firefox 31 ESR: Error: NS_ERROR_FAILURE: Source file: http://localhost/Example/scripts/index.js Line: 18 Similar issue observed on Internet Explorer 11: SCRIPT5022: InvalidStateError The script used for AJAX function call i ...

I require fixed headers that no longer stick once reaching a specific point

I have a setup where the names and occupations of participants are displayed next to their artworks, and I've made it sticky so that as we scroll through the images, the names stay on the left. Now, I want the names to scroll out once the images for e ...

Utilizing data in mongoose: A beginner's guide

I have two database models: User and Conversations. The User model has the following schema: const userSchema = mongoose.Schema({ username: String, logo: String, ..... }) and the Conversation schema is as follows: const conversationSchema = mongo ...

Is the treatment of __proto__ different in the fetch API compared to manual assignment?

When using fetch to retrieve a payload containing a __proto__, it seems that the Object prototype is not affected in the same way as when directly assigning to an object. This behavior is beneficial as it ensures that the Object prototype remains unaffect ...

How can one most effectively parse a JSON object?

I have utilized the $.getJSON method to create a JavaScript object named 'jItems'. Within the page, there is a categorized list of items that correspond to jItems. I want to achieve the functionality where clicking on a category will trigger a fu ...

Differences in background-size among various browsers

Having some trouble with scaling backgrounds on different browsers. Initially designed website on Google Chrome, but background doesn't scale properly when viewed on iPhone or older versions of IE. Started with: background-size: 100% 150%; Then c ...

"Troubleshooting issue: Vue deep watch failing to detect changes in object properties

My initial data consists of a `customer` object. As I input text into various fields, different keys are added to the object. The watcher function triggers properly when a new key is added, but if an existing key is edited with a new value, the watcher doe ...

Getting the input from an HTML editor and inserting it into a textarea using JavaScript

Currently, I am in the process of developing an HTML editor for a project. I have downloaded a program online that I am attempting to customize according to my requirements. However, I am encountering difficulties when trying to retrieve the inner HTML of ...

Create a class for the grandparent element

Is there a way to dynamically add a class to a dropdown menu item when a specific child element is clicked? Here's the HTML structure I have: <ul id="FirstLevel"> <li><a href="#">FirstLevel</a></li> <li>< ...

(Is it even necessary to use a timezone library for this straightforward scenario?)

As I delve into the realm of time zones for the first time, I've heard tales of how challenging it can be for developers. To ensure I am on the right track, I am posing this question as a safeguard to make sure nothing is overlooked. My scenario is q ...

Collecting Images Based on Quantity

Despite using async to download URIs on every request and closing when a certain count is reached, I am still encountering the issue of files not being downloaded properly and exiting before reaching their maximum. Can someone suggest the best solution t ...

The button on my VUE 3 quiz app is not changing to 'Finish' when I reach the final question

Struggling with my Vue 3 quiz app - everything works perfectly until I reach the last question. The button text should change to 'Finish' once the final question is loaded. Despite hours of searching and even using copilot, I still can't fin ...

Animating path "d" with ReactJS and SVG upon clicking in FireFox

Visit this CodePen for more: https://codepen.io/sadpandas/pen/xxbpKvz const [currentScreen, setCurrentScreen] = React.useState(0); return ( <React.Fragment> <div> <svg className="theSvg" width="156" height="6 ...

When you press the submit button, the screen automatically scrolls down but no action is taken

I'm currently utilizing Selenium WebDriver (Java) with the Firefox driver. Upon trying to click the 'Submit' button on a particular page, it only results in scrolling down the screen slightly. The button itself does not register the click, c ...

Is there a way to reverse the animation playback in Angular?

I am working on an animation that involves a box fading from its original color to yellow. However, I would like to achieve the opposite effect: when the page loads, I want the box to start off as yellow and then fade back to its original color. The challe ...

Having Multiple Validation Rulesets with jQuery Validation

I am facing a challenge with a multi-part form that has three different sets of validation rules for each fieldset. The validation rules are defined like this: var paymentValidation = { rules: { "cardInfo.NameOnCard": { ...

What causes TypeScript to automatically infer a default property when dynamically importing a JavaScript file that lacks a default export?

While dynamically importing a javascript file that exports multiple functions (without a default export), I encountered this issue: const sayHi = import('./sayHi.js') I was expecting the type of sayHi to be Promise<{name1: function, name2: fu ...