kenny kenny - 5 months ago 9
jQuery Question

Using jQuery on the select class not all the divs with the same class

Not really sure how to phrase that in the title. Anyways, what I'm saying is that I have three divs with the same class name. I want to add a mouseover function that only works on the select div, not all of them at once. For example :(https://jsfiddle.net/1y2jw2y0/) this makes all the divs show/hide, I only want the selected one to act on the jQuery function.

Html:

<div class="box">
<p class="show">Show</p>
<p class="hide">hide</p>
</div>

<div class="box">
<p class="show">Show</p>
<p class="hide">hide</p>
</div>

<div class="box">
<p class="show">Show</p>
<p class="hide">hide</p>
</div>


Css:

.box {
display: inline-block;
width: 150px;
height: 150px;
border: 1px solid #000;
}

.hide {
display: none;
}


jQuery:

$(document).ready(function() {
$('.box').mouseover(function() {
$('.hide').show();
$('.show').hide();
});
$('.box').mouseleave(function() {
$('.hide').hide();
$('.show').show();
});
});

Answer

Use this to target the "selected" element, then select the child with find() or children():

$(document).ready(function() {
  $('.box').mouseover(function() {
    $(this).children('.hide').show();
    $(this).children('.show').hide();
  });
  $('.box').mouseleave(function() {
    $(this).children('.hide').hide();
    $(this).children('.show').show();
  });
});

JSFiddle Demo