Event conflict when clicking an element

Asked

Viewed 20 times

-1

Greetings,

I’m having a problem clicking a button to bookmark an element: card de receita

When I click on the card it is to open a modal with the recipe info, and when I click on the heart icon it is to bookmark, both methods work, however, there is a conflict when I click on the heart icon, it performs the favorite function, but also performs the modal, That is, the two methods are activated because when I click the icon, I also click the card because it is inside the icon. How do I fix it? Thank you.

  const meal = document.createElement('div')
  meal.classList.add('meal')

  meal.innerHTML = `
    <div class="meal-header">
      ${random ? `<span class="random">Random Recipe</span>` : ''}
      <img src="${mealData.strMealThumb}" alt="${mealData.strMeal}">
    </div>
    <div class="meal-body">
      <h4>${mealData.strMeal}</h4>
      <button class="fav-btn">
        <i class='bx bxs-heart'></i>
      </button>
    </div>
  `
  const btn = meal.querySelector('.meal-body .fav-btn')

  btn.addEventListener('click', () => {
    if(btn.classList.contains('active')){
      removeMealLS(mealData.idMeal)
      btn.classList.remove('active')
    }else{
      addMealLS(mealData.idMeal)
      btn.classList.add('active')
    }

    fetchFavMeals()
  })

  meal.addEventListener('click', () => {
    if (!meal.classList.contains('fav-btn')) {
      showMealInfo(mealData)
    }
  })

  • 1

    this happens because one div is inside the other, could edit the question and put your html?

  • 1

    Please click on [Dit] and put a [mcve] in your question, as Saul commented, so that it is possible to answer it properly.

  • Puts event.stopPropagation(); in the function of the heart event, and places event as a function argument --> (event) => {.

  • Solved, thank you very much!!

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.