main.js 2.15 KB
var caloriesLimit=9999;
function getCheckboxValue(event)  {
  if(event.target.checked)  {
    caloriesLimit = event.target.value;
  }else {
    caloriesLimit=9999;
  }
}

const searchForm = document.querySelector('form');
const searchResultDiv = document.querySelector('.search-result')
const APP_ID = 'fill your own ID';
const APP_KEY = 'fill your own key';
searchForm.addEventListener('submit', function(event){
  if(document.getElementById('name').value.length === 0){
    alert('한글자 이상 입력해주세요');
    event.preventDefault();
  }
  else if(document.getElementById('name').value.length >= 10){
    alert('검색어가 너무 깁니다');
    event.preventDefault();
  }
  else{
    event.preventDefault();
    searchQuery = event.target.querySelector('input').value;
    fetchAPI();
  }
});
async function fetchAPI(){
  const recipeURL = `https://api.edamam.com/search?q=${searchQuery}&app_id=${APP_ID}&app_key=${APP_KEY}`;
  const response = await fetch(recipeURL);
  const data = await response.json();
  boxinfo(data.hits);
  console.log(data);
}
function boxinfo(results){
  let boxsinfo ='';
  results.map(result => {
  const object = {
  	  cal: result.recipe.calories.toFixed(0)
  };
  if(result.recipe.calories>=caloriesLimit){}

  else{
    boxsinfo +=
    `
    <style>
    
    </style>
   
    <div class="item">
      <img src="${result.recipe.image}" alt="">
      <div class="flex-container">
        <h1 class="title">${result.recipe.label}</h1>
        <a href="${result.recipe.url}" target="_blank">View Recipe</a>
        <!--result.recipe.labe에 + home + recipe 한 검색결과 페이지를 버튼에 링크시켜놓음-->
        <a href="https://www.youtube.com/results?search_query=${result.recipe.label}+home+recipe" target="_blank">View Videos</a>
      </div>
      ${(cal => {
        if (cal >= 2000) {
          return `<p style="color:red">${cal}</p>`;
        }
        else if(cal >= 1000 && cal < 2000){
          return `<p style="color:black">${cal}</p>`;
        }
        else {
          return `<p style="color:green">${cal}</p>`;
        }
          })(object.cal)
         }
    </div>
    `}
  })
  searchResultDiv.innerHTML = boxsinfo;
}