Looking to sharpen my skills by working with public APIs in JavaScript. My goal is to sort the list of items alphabetically by the h4
value (food name) when the query is submitted. I attempted to use .sort()
on the response item before using .map()
, but ended up with a blank page. I also tried sorting the div elements with jQuery after the fact, but no luck. I'm new to JavaScript and coding this all in Notepad++, so there might be a better way to approach this that I'm not aware of.
HTML code:
<!DOCTYPE html>
<html>
<form action="search">
<label>Search</label>
<input type="text">
<input type="submit">
<input type="reset">
</form;
<div class="result">
<h3>Result</h3>
</div>
</html>
CSS code:
.result{
display:flex;
flex-wrap:wrap;
}
.item{
min-width:200px;
margin:20px auto;
}
JavaScript code:
var apiKey = "4b314d3e9171fbe99c6cdf16127ba93e";
var apiId = "4c143c55";
var queryItem;
var url = 'https://trackapi.nutritionix.com/v2/search/instant?query=';
var form = document.querySelector('form');
var input = document.querySelector('input[type="text"]');
var result = document.querySelector('.result');
function search(e){
e.preventDefault();
queryItem = input.value;
makeRequest(queryItem);
input.value= "";
}
function reset(){
var node = document.querySelector('.result');
while (node.firstChild) {
node.removeChild(node.firstChild);
}
}
function createFood(name, qty, unit, photo){
var item = document.createElement('div');
var foodName = document.createElement('h4');
var serving = document.createElement('p');
var img = document.createElement('img');
item.classList.add('item');
foodName.innerHTML = name;
serving.innerHTML = qty+' '+unit;
img.src = photo;
result.appendChild(item);
item.appendChild(img);
item.appendChild(foodName);
item.appendChild(serving)
}
function makeRequest(queryItem) {
reset();
xhr = new XMLHttpRequest();
xhr.onload = function() {
var response = JSON.parse(this.responseText);
response.common.map(function(food){
createFood(food.food_name,
food.serving_qty,
food.serving_unit,
food.photo.thumb
)
})
};
xhr.open(
"GET",
url+queryItem,
true
);
xhr.setRequestHeader('x-app-id',apiId);
xhr.setRequestHeader('x-app-key',apiKey);
xhr.send();
}
form.addEventListener('submit', search)
form.addEventListener('reset', reset)