Question

I'm learning jquery and I've been banging my head against this for a few days. I'm trying to create a page that has one large featured image and 4 small thumbnails beneath it. When the user hovers over the thumbnail, I need to change the featured image.

I'm having trouble expressing that when mouse hovers over A, toggle B. But when mouse hovers over C, then toggle D. What's currently happening is that all pshow classes toggle at the same time. Should I be using $(this) to toggle the current element? Should I be using a variable?

I've been searching stackoverflow for a similar question, but I haven't been able to find anything. Sorry if this is a duplicate. Is this the right approach??

JQUERY

<script type="text/javascript"> 
    $(document).ready(function () {
        $('.hover').mouseenter(function() {
        $('.pshow').toggle();
        });
    });
</script>

HTML

<div id="story1">
    <a href="#"><h2 class="hover">Story #1 Text</h2></a>
    <img class="pshow" style="display:none" src="#" >
</div>


<div id="story2">
    <a href="#"><h2 class="hover">Story #1 Text</h2></a>
    <img class="pshow" style="display:none" src="#" >
</div>


<div id="story3">
    <a href="#"><h2 class="hover">Story #1 Text</h2></a>
    <img class="pshow" style="display:none" src="#" >
</div>
Was it helpful?

Solution

I would do it like this...

Put the class into the div, instead of the H2

<div class="hover"  id="story1">

Then your Jquery...

 $('.hover').mouseenter(function() {
     $('.pshow').hide();
    $(this).find('.pshow').toggle();
    });

DEMO HERE

OTHER TIPS

You can use pure CSS for that

For that to work you would need to remove the inline style and set the property in CSS.

As inline styles has more specificity compared to a style defined in CSS.

HTML

<div id="story1">
    <a href="#"><h2 class="hover">Story #1 Text</h2></a>
    <img class="pshow"  src="#" />
</div>

CSS

img{              // .pshow
    display: none;
}

a:hover + img {  // a:hover + .pshow
    display: block;
}

Check Demo

You need to change your selector to select only one element with the class pshow. You can do that like this:

<script type="text/javascript"> 
$(document).ready(function () {
    $('.hover').mouseenter(function() {
         $(this).closest('div').find('img.pshow').toggle();
    });
});
</script>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top