iWillGetBetter
iWillGetBetter

Reputation: 800

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?

Upvotes: 2

Views: 79

Answers (2)

Akash Tomar
Akash Tomar

Reputation: 970

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();
 });

Upvotes: 4

Rajaprabhu Aravindasamy
Rajaprabhu Aravindasamy

Reputation: 67207

You have to use the this reference inside of those event handlers,

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

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

Upvotes: 1

Related Questions