Skip to content

Instantly share code, notes, and snippets.

@LtMama
Last active August 29, 2015 14:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save LtMama/43529b187d595017e444 to your computer and use it in GitHub Desktop.
Save LtMama/43529b187d595017e444 to your computer and use it in GitHub Desktop.
create HTTP request for Username and display response
function slice() {
var newArray = [];
for (var i = 0; i < this.length; i++) {
newArray.push(this[i]);
}
return newArray;
}
var arr = [0, 1, 2, 3, 4];
var bar = slice.call(arr);
[0,1,2,3,4,5].reduce(function (sum, elem) {
return sum + elem
}, 0);
[2,5,3,22,4,56,7].reduce(function (max, elem) {
return Math.max(max, elem);
}, -Infinity);
// github user finder example
var input;
function getGitHubHandle() {
return input.value;
}
function sendRequest() {
var username = getGitHubHandle();
var url = 'https://api.github.com/users/' + username;
var xhr = new XMLHttpRequest();
xhr.open("GET", url, true);
xhr.onload = function(){
if(xhr.status >= 399) {
return alert('BOOOOO');
}
var data = JSON.parse(xhr.responseText);
formatResult(data)
};
xhr.send();
}
function formatResult(data){
var container = document.getElementById('container')
var profile = document.createElement('div');
profile.classList.add('profile');
var h2 = document.createElement('h2');
var avatar = document.createElement('div');
var information = document.createElement('div');
profile.appendChild(h2);
profile.appendChild(avatar);
profile.appendChild(information);
var usernameContent = document.createTextNode(data.login)
var img = new Image();
img.src = data.avatar_url;
h2.appendChild(usernameContent)
avatar.appendChild(img)
container.appendChild(profile);
}
function removeProfile(){
var profiles = document.getElementsByClassName('profile');
var length = profiles.length;
if(length === 0 ){
return;
}
var parent = profiles[0].parentNode
for(var i = 0; i < length; i++) {
parent.removeChild(profiles[i]);
}
}
$(document).ready(function(){
input = document.getElementById('username');
input.addEventListener('keypress', function (event){
if(event.which === 13){
removeProfile();
sendRequest();
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment