pleaseForgiveCodeNoob pleaseForgiveCodeNoob - 2 months ago 6
HTML Question

how to use classes to refer to the correct element in jquery

I have cards displayed on the website. I want to display a label on whichever card I am currently hovering on.

main.js

$('.card').on("mouseover", function () {
$('.ui.right.corner.label').show();
});
$('.card').on("mouseout", function () {
$('.ui.right.corner.label').hide();
});


This appeared to work fine until I realised that specific card's label is shown every time I hover on ANY of the cards.

Index.php

<!--first card-->
<div class="card" onclick="window.location='product.php';">

<img src="img/test1.jpg" class="image">
<a class="ui right corner label">
<i class="heart icon"></i>
</a>
</div>

<!--second card-->
<div class="card" onclick="window.location='product.php';">

<img src="img/test2.jpg" class="image">
<a class="ui right corner label">
<i class="heart icon"></i>
</a>
</div>

<!--third card-->
<div class="card" onclick="window.location='product.php';">

<img src="img/test3.jpg" class="image">
<a class="ui right corner label">
<i class="heart icon"></i>
</a>
</div>


I have currently fixed the child element problem by using Rajaprabhu's answer. However, the label is now appearing on the website by default. I am using
.hide
to hide them but is there a better way to not show the label when website is loaded?

Answer

That is because you are showing and hiding all the elements with that particular class. Try this method.

 $('.card').on("mouseover", function () {
  $(this).children("a").show();
 });
 $('.card').on("mouseout", function () {
  $(this).children("a").hide();
 });
Comments