Twitter API prototype

Prototype with new Twitter API

by Ramesh Kanagaraj

HTML

<script src="https://platform.twitter.com/widgets.js"></script>
<button id="create-widget">Create Timeline</button>
<label for="screen_name">using Twitter user: @</label>
<input type="text" id="screen_name" value="NR_Tracker" />
<p></p>
<div id="wrapper">
    <div id="widget" class="widget-div"></div>
    <div id="loading" class="widget-loading">
        <p>Loading...</p>
    </div>
    <div id="initial" class="widget-initial"></div>
</div>
<button id="widget-refresh">Refresh</button>

CSS

.widget-div {
    width: 100%;
    display: none;
}
.widget-loading {
    display: none;
    padding-top: 1em;
    padding-left: 5em;
    font-size: 1.4em;
}
.widget-initial {
    // nothing for now
}

JavaScript

$("#create-widget").on("click", function (e) {
    // prevent a second click while processing
    // can be important when you are loading data from a server
    // and when you are adding even more time for fadeOut/fadeIn
    $(this).prop("disabled", true);

    // show loading..., remove any prior widget
    $("#widget").hide();
    $("#loading").show();
    $("#widget").empty();

    // create a twitter timeline widget
    // see https://dev.twitter.com/web/javascript/creating-widgets
    twttr.widgets.createTimeline(
        "317788461761429504", // Widget ID from Ed's twitter account
    $("#widget").get(0), // use .get(0) to access HTML Element
    {
        height: 300,
        screenName: $("#screen_name").val()
    }).then(function (element) {
        // called when timeline has been successfully created
        console.log("timeline creation complete");

        // adjust width since twitter uses 520px as maximum
        // see https://dev.twitter.com/web/embedded-timelines#dimensions
        $(element).css("width", "100%");

        // stop saying "loading..." and show the widget
        $("#loading").fadeOut("slow", function () {
            // when fadeOut is complete...
            $("#widget").fadeIn("slow", function () {
                // when fadeIn is complete, finally re-enable the button
                $("#create-widget").prop("disabled", false);
            });
        });
    }, function (status) {
        // called on failure, not sure what arguments twitter passes
        // it appears to pass back the HTTP status from the API
        // see https://dev.twitter.com/overview/api/response-codes
        // so ((typeof status) === "number") 
        // I can also see that the JSON in the HTTP response header has
        // an error message (string) which makes sense since this library call
        // is presumably using the API (which includes an error message as well)
        // but they don't seem to pass that to this callback
        //...