I need help creating a conditonal pop up modal when no results are found from an API call.
When the API returns a result: length:0 from the array I would like a modal to appear that says no results found.
The CSS is working. This is my HTML + JS
HTML
<div class="modal" id="myModal">
<div class="modal-content">
<span class="close">×</span>
<p>Sorry no results found</p>
</div>
</div>
<button class="btn" id="searchBtn">Search</button>
JS
var modal = document.getElementById("myModal");
var btn = document.getElementById("searchBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function(){
// for (var i = 0; i < data.length; i++) {
// if (data[i].length === 0) {
modal.style.display = "block";
};
span.onclick = function(){
modal.style.display = "none";
};
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
};
API call code
var newRecipe =
'https://api.spoonacular.com/recipes/findByIngredients?ingredients='+
allIngreds + '&number=10&apiKey=39791063581a4d96a908bb19745b3f64';
fetch(newRecipe)
.then(response => {
if (!response.ok){
throw Error("ERROR")
};
return response.json();
})
.then(data => {
console.log(data);
});
Based on the api call that you posted, it should be sth like this
fetch(newRecipe)
.then(response => {
if (!response.ok){
throw Error("ERROR")
};
return response.json();
})
.then(data => {
console.log(data);
if (data.length === 0) {
modal.style.display = "block";
} else {
modal.style.display = "none";
}
});