laaposto
laaposto

Reputation: 12213

jQuery select child with class only not all

I want to show some images when i hover on others. So far i have tried this:

$('.image').hover(function() {
    $('.icon').stop().animate({"opacity": 1}); 
},function() { 
    $('.icon').stop().animate({"opacity": 0}); 
});

But i dont want to show all images when i hover on one image.

I have this demo

Now i want when i hover to an image with class .image, to change opacity only in the image with class .icon that is clild of the one i hover, not all.

I hover the first image only up image changes opacity, not both. I hover the second image, only down image change opacity

Any ideas?

EDIT:

I forgot to mention that i want the image that is showing up to stay when i hover over it. Actually the two images are one inside each other. See updated fiddle

Upvotes: 1

Views: 70

Answers (3)

Jai
Jai

Reputation: 74738

You can use .siblings() this way:

$('.image, .icon').hover(function(e) {
   if(e.type === 'mouseenter' && $(e.target).is('.image')){
      $('.icon').stop().animate({"opacity": 0}); 
      $(this).siblings('.icon').stop().animate({"opacity": 1}); 
   }
   if(e.type === 'mouseleave' && $(e.target).is('.icon')){
      $('.icon').stop().animate({"opacity": 0});   
   }
});

and change your context to current selector with $(this)

UPDATED Fiddle demo

Upvotes: 1

Pranav C Balan
Pranav C Balan

Reputation: 115212

Try this code

$('div').hover(function() {
    $(this).children('.icon').stop().animate({"opacity": 1}); 
},function() { 
    $(this).children('.icon').stop().animate({"opacity": 0}); 
});

FIDDLE

Upvotes: 1

venkatprasad
venkatprasad

Reputation: 1

you can use jquery $(this) to indicate current class element and you can use parent().find('element or class or id name') to traverse the appropriate element

$('.image').hover(function() {
$(this).parent().find('.icon').stop().animate({"opacity": 1}); 
},function() { 
$(this).parent().find('.icon').stop().animate({"opacity": 0}); 
});

Upvotes: 0

Related Questions