0

I am wondering, can this function be modified to run when the page loads instead of when the button(s) with class="statusbutton" is clicked?

<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$( document ).ready(function() {

    $( ".statusbutton" ).each(function(index){
        $(this).on("click", function(){
            var btnObj = this;

            $.getJSON( 'http://api.justin.tv/api/stream/list.json?channel=' + $(this).attr('id') + '&jsonp=?', function(twitchData) {

        if (typeof(twitchData[0]) !== 'undefined' && typeof(twitchData[0].stream_type) !== 'undefined') {
            if (twitchData[0].stream_type == 'live') {
                // live
                $(btnObj).css('background-color', '#00FF00');
            } else {
                // something other than live
                $(btnObj).css('background-color', '#f11');
            }
        }else{
            // no data or invalid data from twitch
            $(btnObj).css('background-color', '#f11');
        }



});

        });
    });
});

</script>
2
  • Do you have a question? I don't understand what you are asking. May 5, 2014 at 17:51
  • there, the thread now reflects my current issue. May 5, 2014 at 18:26

1 Answer 1

0

Assuming your buttons should retain the ability to trigger the AJAX request when clicked. You can just manually fire the click event on your .statusbutton buttons right after DOM ready and after binding the event handlers.

$(document).ready(function() {

    $(".statusbutton").each(function(index) {

        $(this).on("click", function() {
            var btnObj = this;
            $.getJSON('http://api.justin.tv/api/stream/list.json?channel=' + $(this).attr('id') + '&jsonp=?', function(twitchData) {
                if (typeof(twitchData[0]) !== 'undefined' && typeof(twitchData[0].stream_type) !== 'undefined') {
                    if (twitchData[0].stream_type == 'live') {
                        // live
                        $(btnObj).css('background-color', '#00FF00');
                    } else {
                        // something other than live
                        $(btnObj).css('background-color', '#f11');
                    }
                } else {
                    // no data or invalid data from twitch
                    $(btnObj).css('background-color', '#f11');
                }
            });
        });

    }).trigger('click'); // manually trigger 'click' to initiate AJAX request  

});
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.