Reputation: 323
I am trying to replace a background image using jQuery.
The image is being called from an API, below is a fiddle with the JSON data.
https://jsfiddle.net/m15xg45j/
This JS Fiddle contains the full code all HTML, CSS and JS
https://jsfiddle.net/bsu6m5es/2/
My JS
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key' : "***",
'q' : "health"
});
$.ajax({
url: url,
method: 'GET',
}).done(function(result){
var articles = result.response.docs;
for(var i=0; i<articles.length; i++){
$("h2").each(function(index, el){
$(el).html(articles[index].headline.main);
});
$(".article--snippet").each(function(index, el){
$(el).html(articles[index].snippet);
});
$(".post").each(function(index, el){
$("el").css("background", "url(" + articles[index].thumbnail +")");
});
// console.log(articles[i].url);
$(".linked--headline").each(function(index, el){
$(el).attr("href", articles[index].web_url);
});
// console.log(articles[i].web_url);
}
}).fail(function(err){
throw err;
});
Upvotes: 0
Views: 1004
Reputation: 1416
Instead of using the 'done' method, run the success method:
Based on what the data structure you have presented, you need to run a for loop and use filter over the multimedia property. Check the code
https://jsfiddle.net/bsu6m5es/3/
var url = "https://api.nytimes.com/svc/search/v2/articlesearch.json";
url += '?' + $.param({
'api-key' : "67dac4e994164fca920f7a8420e28dc2",
'q' : "health"
});
$.ajax({
url: url,
method: 'GET',
success : function(result){
var articles = result.response.docs;
for(var i=0; i<articles.length; i++){
$("h2").each(function(index, el){
$(el).html(articles[index].headline.main);
});
$(".article--snippet").each(function(index, el){
$(el).html(articles[index].snippet);
});
$(".post").each(function(index, el){
$("el").css("background", "url(" + articles[index].thumbnail +")");
});
// console.log(articles[i].url);
$(".linked--headline").each(function(index, el){
$(el).attr("href", articles[index].web_url);
});
/// Your thumbnails:
for (var i=0;i<r.response.docs.length;i++)
{
var thumbUrl = r.response.docs[i].multimedia.filter(function(el){ return el.subtype='thumbnail'})[0].url;
// e.g: thumbUrl = 'images/2017/02/28/science/28BRODY/28BRODY-thumbWide.jpg'
}
// console.log(articles[i].web_url);
}
}).fail(function(err){
throw err;
});
Upvotes: 1