sábado, 18 de mayo de 2013

Listar noticias de Twitter con jQuery

Si se desea listar las noticias publicadas por ciertos usuarios de Twitter, se puede usar este script.

//Twitter
function twFetch() {
    jQuery(document).ready(function($) {
        //Set Url of JSON data from the facebook graph api. make sure callback is set with a '?' to overcome the cross domain problems with JSON
        var url = "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=wimarbueno&include_rts=true&include_entities=true&count=10&callback=?";

        //Use jQuery getJSON method to fetch the data from the url and then create our unordered list with the relevant data.
        $.getJSON(url, function(json) {
            var html = "<ul>";
            //loop through and within data array's retrieve the message variable.            
            $.each(json, function(i, tw) {
                html += "<li><div class=\"views-field views-field-created\"><span class=\"field-content\">Update " + timeAgo(tw.created_at) + "</span></div><a href=\"https://twitter.com/RecycleCartons\" target=\"_blank\">" + tw.text + "</a></li>";
            });
            html += "</ul>";

            //A little animation once fetched
            $('#twitter-list').animate({
                opacity: 0
            }, 500, function() {
                $('#twitter-list').html(html);
            });

            $('#twitter-list').animate({
                opacity: 1
            }, 500);
        });
    });
}



/**
 * relative time calculator FROM TWITTER
 * @param {string} twitter date string returned from Twitter API
 * @return {string} relative time like "2 minutes ago"
 */
function timeAgo(dateString) {
    var rightNow = new Date();
    var then = new Date(dateString);

    if (jQuery.browser.msie) {
        // IE can't parse these crazy Ruby dates
        then = Date.parse(dateString.replace(/( \+)/, ' UTC$1'));
    }

    var diff = rightNow - then;
    var second = 1000,
            minute = second * 60,
            hour = minute * 60,
            day = hour * 24,
            week = day * 7;

    if (isNaN(diff) || diff < 0) {
        return ""; // return blank string if unknown
    }
    if (diff < second * 2) {
        // within 2 seconds
        return "right now";
    }
    if (diff < minute) {
        return Math.floor(diff / second) + " seconds ago";
    }
    if (diff < minute * 2) {
        return "about 1 minute ago";
    }
    if (diff < hour) {
        return Math.floor(diff / minute) + " minutes ago";
    }
    if (diff < hour * 2) {
        return "about 1 hour ago";
    }
    if (diff < day) {
        return  Math.floor(diff / hour) + " hours ago";
    }
    if (diff > day && diff < day * 2) {
        return "yesterday";
    }
    if (diff < day * 365) {
        return Math.floor(diff / day) + " days ago";
    }
    else {
        return "over a year ago";
    }
} // timeAgo()

No hay comentarios:

Publicar un comentario