I have this code that gets an image from the Minecraft API via uuid or username. It gets the value from an input tag.
HTML:
<input type="text" id="nameinput" placeholder="Username"/>
<img src="" id="display"/>
<script type="text/javascript" src="/JS/login-page.js"></script>
Js:
document.querySelector("#nameinput").oninput = function(){
var request = new XMLHttpRequest();
request.onload = function() {
// Grab data and assing feilds
var response = JSON.parse(request.responseText);
var uuid = response.id;
if (typeof(uuid) == "undefined") {
response.id = "steve";
}
document.querySelector("#display").src = "https://crafatar.com/avatars/" + uuid + "?overlay&size=512";
};
request.open("GET", "https://api.year4000.net/minecraft/" + document.querySelector("#nameinput").value, true);
request.send();
}
Basically, I want to move the image from the API over to display it in the image tag. How do I do this?
I recommend using addEventListener instead of setting the oninput attribute.
const nameInput = document.querySelector("#nameinput");
const img = document.querySelector("#display");
nameInput.addEventListener('input', function () {
// Don't do anything if the value is empty
if (this.value === '') return;
const request = new XMLHttpRequest();
request.onload = function () {
const response = JSON.parse(request.responseText);
const { id } = response;
img.setAttribute('src', `https://crafatar.com/avatars/${id}?overlay&size=512`);
};
request.open("GET", "https://api.year4000.net/minecraft/" + this.value, true);
request.send();
});
<input type="text" id="nameinput" placeholder="test123" /><br>
<img id="display" src="" />