miranda
miranda

Reputation: 69

How to dynamically reveal JSON data on click from an API?

I have data from a Tumblr API that I've successfully parsed, until I introduced tags within the body description. (This includes images, hyperlinks, etc)

What I'm essentially doing is creating a list of blog titles. A blog description is dynamically revealed depending on which title is clicked. I feel that this code breaks because of an issue with quotations, but I'm not sure how to work around this.

HERE IS A CODEPEN demonstrating the issue with full code.

This is just a partial look at the error:

      //...
      $.each(inner, function(i, obj) {

          title = inner[i].Title
          description = inner[i].Description

     // Source of the error
     // data-description includes an <a> tag that breaks the code
          $('<div class = "title-list" data-title = "<h3>' + title + '</h3>" data-description="' + description  + '">' + title + '</div>').appendTo(monthblogList)

        })
      })
    });

    function showBlogEntry(element){
      var t = $(element).data('title')
      var ds = $(element).data('description')

      blogEntry.empty()

      $(t).appendTo(blogEntry)
      $(ds).appendTo(blogEntry)
    }
}

Again, I would recommend looking at CODEPEN to get a better understanding. I've included an a tag on the first blog post, to show the issue. Here is original the blog post.

Here is one solution I thought of:

if ($(description).has("a")) {
  // do something
}

But still unsure of how to fix the issue.

I need to grab information from the title and description variables and have it's data revealed on click depending on which title the user clicks. This was one solution, though it may not be the best. If there are other solutions aside from data tags, that would be appreciated. Thanks in advance.

Upvotes: 1

Views: 117

Answers (1)

Jeremy Dejno
Jeremy Dejno

Reputation: 106

Instead of storing the data in the "data-" attribute of the HTMLDivElement, just keep a reference to JSON response from the API in your javascript and store an index or id in the "data-" attribute (possibly "data-post-id")

var blogData = [{Title: .., Description: ...}, ...]; //Data from JSON Response

...
...

$('<div class = "title-list" data-post-id =' + postId +'>' + title + '</div>').appendTo(monthblogList);

...
...    

function showBlogEntry(element){
      var id = $(element).data('post-id')
      var close = $('<span id = close> x </span>')

      blogEntry.empty()

      $(close).appendTo(blogEntry)
      $('<h3>' + blogData[id].Title + '</h3>').appendTo(blogEntry)
      $(blogData[id].Description).appendTo(blogEntry)

      $("#close").on("click", function (event) {
        blogEntry.empty()
        about.fadeIn()
      });
    }

Upvotes: 2

Related Questions