Can someone please explain to me what this code does?

Can someone please explain to me what this code does?
0

#1

I looked at the example code, plus some others that I found elsewhere and I am lost on the JavaScript and jQuery. Here is the example’s js/jq code:

function inIframe() {
  try {
    return window.self !== window.top;
  } catch (e) {
    return true;
  }
}

var colors = ['#16a085', '#27ae60', '#2c3e50', '#f39c12', '#e74c3c', '#9b59b6', '#FB6964', '#342224', "#472E32", "#BDBB99", "#77B1A9", "#73A857"];
var currentQuote = '',
  currentAuthor = '';

function openURL(url) {
  window.open(url, 'Share', 'width=550, height=400, toolbar=0, scrollbars=1 ,location=0 ,statusbar=0,menubar=0, resizable=0');
}

function getQuote() {
  $.ajax({
    headers: {
      "X-Mashape-Key": "OivH71yd3tmshl9YKzFH7BTzBVRQp1RaKLajsnafgL2aPsfP9V",
      Accept: "application/json",
      "Content-Type": "application/x-www-form-urlencoded"
    },
    url: 'https://andruxnet-random-famous-quotes.p.mashape.com/cat=',
    success: function(response) {
      var r = JSON.parse(response);
      currentQuote = r.quote;
      currentAuthor = r.author;
      if (inIframe()) {
        $('#tweet-quote').attr('href', 'https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent('"' + currentQuote + '" ' + currentAuthor));
        $('#tumblr-quote').attr('href', 'https://www.tumblr.com/widgets/share/tool?posttype=quote&tags=quotes,freecodecamp&caption=' + encodeURIComponent(currentAuthor) + '&content=' + encodeURIComponent(currentQuote));
      }
      $(".quote-text").animate({
          opacity: 0
        }, 500,
        function() {
          $(this).animate({
            opacity: 1
          }, 500);
          $('#text').text(r.quote);
        });

      $(".quote-author").animate({
          opacity: 0
        }, 500,
        function() {
          $(this).animate({
            opacity: 1
          }, 500);
          $('#author').html(r.author);
        });

      var color = Math.floor(Math.random() * colors.length);
      $("html body").animate({
        backgroundColor: colors[color],
        color: colors[color]
      }, 1000);
      $(".button").animate({
        backgroundColor: colors[color]
      }, 1000);
    }
  });
}
$(document).ready(function() {
  getQuote();
  $('#new-quote').on('click', getQuote);
  $('#tweet-quote').on('click', function() {
    if (!inIframe()) {
      openURL('https://twitter.com/intent/tweet?hashtags=quotes&related=freecodecamp&text=' + encodeURIComponent('"' + currentQuote + '" ' + currentAuthor));
    }
  });
  $('#tumblr-quote').on('click', function() {
    if (!inIframe()) {
      openURL('https://www.tumblr.com/widgets/share/tool?posttype=quote&tags=quotes,freecodecamp&caption=' + encodeURIComponent(currentAuthor) + '&content=' + encodeURIComponent(currentQuote));
    }
  });
});

I am trying to figure out why this code is so complicated. Does it need to be this complicated? How do you implement a basic jQuery callback to get data from an API? I know how to get it to post a tweet, etc but this seems more complicated than it needs to be.

Need some help.

Specifically the first part of the code with try and catch. Not sure what that does.

Looking over the code some more I understand more of it. Had to go to Treehouse and look at the jQuery API docs. But still, this seems very…more than what is needed tbqh.


#2

It’s checking to see if the active window is in an iFrame. It uses that information at the end when you try to share the quote. If It’s not in an iFrame then it pops open a new window to handle the Twitter/Tumblr sharing without completely redirecting the page.


#3

If I wanted to use a jQuery callback to grab data from an API, could you give me a simple example of that? Not sure I am grokking it from this example.


#4

This example is actually pretty good, except for the inIframe business which isn’t necessary.

$.ajax Is the longer version of $.getJSON and it expects an object containing things like headers and what to do if it encounters an error or is successful.

I’m on mobile now, so it’s hard to give a fuller answer.

You could try deleting everything from the success part and just have console.log(response) in the function instead, then you should see what object is handed to you. You may need to JSON.stringify the response first.

If you don’t get better help from someone else, I’ll jump back on my computer later.


#5

I couldn’t resist :slight_smile:

Check this pen for a really basic implementation.

I used a different API that has slightly different requirements, but it doesn’t need an API key: http://codepen.io/Malgalin/pen/XKERax?editors=0012


#6

Thanks so much Jackson.

Would have gotten to you sooner but the forum was down this morning.


#7

Hello,

Why did he had to use a try/ catch structure ?

Doing function inIframe() { return window.self !== window.top; } could not be enough?


#8

I am wondering the same. Plus I don’t understand the if(!inIframe) part. If that condition returns false, means the following statements won’t execute, right ?