Struggling to create a Pinterest-like webpage using masonry.js? Having trouble appending unique descriptions to each image in your code? You're not alone. The last line of the code seems to be causing issues, but the solution isn't clear. By consolidating all description tags into one span for each image, you may be missing out on individualized details.
Looking at various StackOverflow inquiries like jQuery: Add element after another element and add image/s inside a div with jquery, but haven't found a resolution yet.
View the entire pen here: http://codepen.io/OG/pen/VLEXgz
HTML
<body>
<h1>Camper Stories</h1>
<div id="content"></div>
</body>
CSS
h1{
text-align:center;
font-family: 'Lobster', cursive; font-size:80px;
color:purple;
}
#content {
width: auto;
margin: 0 auto;
}
.item {
display: inline-block;
float: left;
width: 300px;
height:300px;
margin: 2em;
position:relative;
}
.item img {
width: 300px;
height: auto;
}
JS
var url = 'http://www.freecodecamp.com/stories/hotStories';
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
var myArr = JSON.parse(xmlhttp.responseText);
myFunction(myArr);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(arr) {
var i;
var headlines = [];
//loop through json get need attributes
//for(i = 0; i < arr.length; i++){
for (i = 0; i < 5; i++) {
var headline = arr[i].headline;
headlines.push(headline);
var authorImg = arr[i].author.picture;
//console.log(img);
//error function
//if there is no thumbnail link the get author image
if (img === "") {
$('#content').append('<div class="item">' + '<a href="' + link + '">' + '<img id="myImg" src="' + authorImg + '" alt="' + headline + '" />' + '</a>' + '</div>');
} else {
//if there is a thumbnail image then use that image
$('#content').append('<div class="item" id="hi">' + '<a href="' + link + '">' + '<img id="myImg" src="' + img + '" alt="' + headline + '" />' + '</a>' + '</div>');
//if there is a 404 error with loading the thumbnail image then use author's image
$('img').one('error', function () {
this.src = '' + authorImg;
})
}
$(arr[i].headline).insertAfter("img");
}
}