Solution 1 :

Plain CSS will do. hide selector should not be an id, because it is appearing multiple times on the page.

.card__food:hover > .hide {
    visibility: 'visible';
}
.card__food > .hide {
    visibility: 'hidden';
}

Problem :

I have these 9 cards, for each cards when the mouse is over the component I would hide/visible
.

``
<div class="cards__food">
    <% @foods.each do |food| %>
      <%= link_to(foods_path) do %>
        <div class="card__food">
          <div class="card__food-img" style="background-image: url(<%= food.image_url %>);"></div>
          <h3><%= food.name.upcase %></h3>
          <div id="hide">
            <p>ORDER</p>
          </div>
        </div>
        <% end %>
      <% end %>
  </div>

#hide {
  visibility: hidden;
}
  • I selected each cards. Each have been assigned to a variable cards.
  • To have effect on i did the same things

Here is my trouble, without forEach i can’t use addEventListener.

the console said:

TypeError: cards.addEventListener is not a function

So i used forEach. But when the mouse is over a card only the first card trigger and render visible or hide:

          <div id="hide">
            <p>ORDER</p>
          </div>

depend on mouseover/mouseout

const addOrderToFood = () => {
  const cards = document.querySelectorAll(".card__food");
  const order = document.getElementById('hide');
  if (cards) {
    cards.forEach(card => {
      card.addEventListener("mouseover", (event) => {
        console.log(event)
        order.style.visibility='visible';
      })
      card.addEventListener("mouseout", (event) => {
        console.log(event)
        order.style.visibility='hidden';
      })
    })

  }

}

I can’t find a issue and I really want to beat this piece of code haha ! 😀

Comments

Comment posted by Sonu Bamniya

the problem is you are attaching the

Comment posted by augustin brun

So i should remove forEach() ?

Comment posted by Parnab Sanyal

Yes, remove it.

Comment posted by augustin brun

.card__food > .hide { &:hover { visibility: ‘visible’; } } .card__food > .hide { visibility: ‘hidden’; }

Comment posted by augustin brun

if i remove forEach i have this error: TypeError: cards.addEventListener is not a function

Comment posted by augustin brun

Thank’s for your help you make it so simple ! haha

By

Leave a Reply

Your email address will not be published. Required fields are marked *