I have this little bit of code to check the status of a Twitch stremer.
$(document).ready(function () {
// initialize user login and status variables
var login = '';
var twitchStatusLinks = $('.twitch-status');
var twitchStatusResponse = $('.twitch-response');
var user_name = getUrlParameter('user_name');
// loop through each link
twitchStatusLinks.each(function (index, value) {
var twitchStatusLink = $(this);
twitchStatusResponse.html('<span ></span>');
login = twitchStatusLink.attr('href').split('/');
login = login[3]; // get username from link
// check for parameter override - useful for iframe links
if (user_name !== undefined) {
login = user_name;
twitchStatusLink.attr('href', 'https://twitch.tv/' login);
}
// use ajax to call Twitch API
$.ajax({
type: 'GET',
url: 'https://api.twitch.tv/helix/streams?user_login=' login,
headers: {
"Client-ID": "REDACTED",
"Authorization": "Bearer REDACTED"
},
success: function (data) {
console.log(data);
var status = ""; // default if data null
if (data.data[0] != undefined) status = data.data[0]['type']; //TYPE contains the word 'live' when streamer online
twitchStatusResponse.addClass(status);
twitchStatusResponse.find('.text').text(status);
}
});
});
});
// get parameter from url - https://stackoverflow.com/a/21903119/2510368
var getUrlParameter = function getUrlParameter(sParam) {
var sPageURL = window.location.search.substring(1);
var sURLVariables = sPageURL.split('&');
var sParameterName;
for (var i = 0; i < sURLVariables.length; i ) {
sParameterName = sURLVariables[i].split('=');
if (sParameterName[0] === sParam) {
return sParameterName[1] === undefined ? true : decodeURIComponent(sParameterName[1]);
}
}
};
That all works great. But I am stuck trying to hide the SPAN element if the Data array is undefined (when a streamer is offline, Twitch returns an empty array).
<span style="background:Tomato"></span>
I only want the SPAN element to be shown when the Data array is defined. I am definitely no expert and I have been unable to make it work so far. Can anyone shed some light please?
CodePudding user response:
in the ajax success function you will check the size of the array and hide the span if needed:
if(data.data.length == 0) $('span.twitch-response').css('display', 'none')