Reputation: 337
I'm doing a simple project where I'm showing my github profile in vanilla javascript.
let requestURL = 'https://api.github.com/users/fcfidel';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var githubInfo = request.response;
populateHeader(githubInfo);
//showGithubInfo(githubInfo);
}
function populateHeader(jsonObj) {
var myH1 = document.createElement('h1');
//myH1.textContent = jsonObj['login'];
myH1.textContent = `<img src="${jsonObj['avatar_url']}" />`;
image.appendChild(myH1);
var myPara = document.createElement('p');
myPara.textContent = 'Name: ' + jsonObj['name'] + ' // Formed: ' + jsonObj['created_at'];
image.appendChild(myPara);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="application/javascript" src="main.js"></script>
</head>
<body>
<div class="image"></div>
<div class="name"></div>
<script>
var image = document.querySelector('.image');
var name = document.querySelector('.name');
</script>
</body>
</html>
I am trying to find a way to return the in javascript but I just can't find a way :(
The only way I kind of found a way was with the template literal it works but not that way I want, it does return what I want but...
this is the result:
I know the solution is something really simple, but I just can't even no more...
this is the result that I want:
Im learning javascript Im still a noob... Im doing the exercises from the MDN :/
Upvotes: 2
Views: 509
Reputation: 7367
Set the image source instead of adding it to the div. Also the backticks are not helping!
Add image tag and modify the ajax call to use:
document.querySelector('#my-image').src = jsonObj['avatar_url'];
let requestURL = 'https://api.github.com/users/fcfidel';
var request = new XMLHttpRequest();
request.open('GET', requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var githubInfo = request.response;
populateHeader(githubInfo);
//showGithubInfo(githubInfo);
}
function populateHeader(jsonObj) {
var myH1 = document.createElement('h1');
//myH1.textContent = jsonObj['login'];
//myH1.textContent = `<img src="${jsonObj['avatar_url']}" />`;
//image.appendChild(myH1);
var myPara = document.createElement('p');
myPara.textContent = 'Name: ' + jsonObj['name'] + ' // Formed: ' + jsonObj['created_at'];
image.appendChild(myPara);
document.querySelector('#my-image').src = jsonObj['avatar_url'];
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script type="application/javascript" src="main.js"></script>
</head>
<body>
<div class="image">
<img id="my-image" src="" />
</div>
<div class="name"></div>
<script>
var image = document.querySelector('.image');
var name = document.querySelector('.name');
</script>
</body>
</html>
Upvotes: 3