0

I am trying to create a pinterest like webpage using mansory.js and I am having trouble appending the unique description to each image. I know that the last line of my code is wrong but I have no idea how to fix it. I am basically adding all of the description tags into one span for each image.

I've tried looking at several other stackoverflow questions such as jQuery: Add element after another element and add image/s inside a div with jquery but with no luck.

My entire pen is 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");
    }
}
Community
  • 1
  • 1
Zaynaib Giwa
  • 5,366
  • 7
  • 21
  • 26
  • Post the sample response from your ajax and the expected HTML output. – lshettyl Jul 26 '15 at 08:19
  • I think you should look more into this, var hl = $("").text(arr[i].headline); $("img").append(hl); – TheGeekYouNeed Jul 26 '15 at 08:22
  • Why you're using `XMLHttpRequest` when you have jQuery available? – Andreas Jul 26 '15 at 08:31
  • @TheGeekYouNeed You can't append something to ``, they don't have content. – Barmar Jul 26 '15 at 08:38
  • 1
    Use `
    ` and `
    ` - [The figure & figcaption elements](http://html5doctor.com/the-figure-figcaption-elements/)
    – Andreas Jul 26 '15 at 10:27
  • @Andreas yeah XMLHttpRequest is not ideal and I know I could have use other methods. I am very knew to the world of javascript and jQuery. I just wanted to play around with different ways with getting json requests. – Zaynaib Giwa Jul 26 '15 at 15:25

2 Answers2

2

See http://codepen.io/anon/pen/YXJvEK Is that what you mean? Append the headline after the corresponding image only?

$("<span>" + arr[i].headline+"</span>").insertAfter($("img").eq(i));
artm
  • 8,554
  • 3
  • 26
  • 43
  • This is exactly what I was what I meant. I never knew that the eq() function existed. I'll keep this method in mind for the future. Thank you – Zaynaib Giwa Jul 26 '15 at 15:30
2

You should build your elements like this:

var wrapper = $("<div />");
var link = $("<href />");
var img = $("<img />");
...

Then add attributes and classes needed and append them to each other.

link.append(img);
wrapper.append(link);
...

In that way your code gets much more maintainable and you can append your span easily to your img (don't know exactly where you want the description).

Edit, since I've got my hands on a pc, here's the code you could use.

function myFunc (data) {
  if(typeof data === "undefined") return; // output some error
  for (var i = 0; i < data.length; i++) {
    var item = data[i];
    var upVote = item.rank;
    var href = item.link;
    var image = (item.image === "") ? item.author.picture : item.image;
    var headline = item.headline;

    // build elements
    var wrapper = $("<div />");
    var link = $("<a />");
    var img = $("<img />");
    var description = $("<span />");

    // add attributes and classes
    wrapper.addClass("item");
    link.attr("href", link);
    // you can also set multiple attributes at once
    img.attr({"src": image, "alt": headline}); 
    description.text(headline); // text(string) adds string to element

    // append elements onto each other
    link.append(img);
    wrapper.append(link, description);

    $("div.content").append(wrapper); // attach elements to DOM
  }
}
TobiasJ
  • 107
  • 1
  • 6
  • What do you call the logic statement for the image variable? I've seen it a lot in other people's code but I never understand what it was called. Also thank you for show me this jquery pattern for building elements on the page. It's way prettier on the eyes. – Zaynaib Giwa Jul 26 '15 at 16:19
  • You can read the specs on https://developer.mozilla.org/de/docs/Web/JavaScript/Reference/Operators/Conditional_Operator Basically it is: variable = (if condition) ? trueValue : falseValue; – TobiasJ Jul 26 '15 at 16:38