JQuery - making a list 3 or more img toggles go to their default image when one of them is toggled via click event

StackOverflow https://stackoverflow.com/questions/18153909

  •  24-06-2022
  •  | 
  •  

Question

Here's my jsfiddle.

I can get two divs to toggle and then have the other div reset to it's original img, but I can't do this for 3 or more divs. I'm doing something wrong with my eq methods, but not sure what.

HTML:

<div class="home">
    <img src="http://www.misfitpsycles.com/blog/wp-content/uploads/2011/09/Red-Circle.jpg">
    <img style="display:none;" src="http://tribute.dbclay.com/img/badjorx/black-circle.jpg">
</div>
<div class="myPlayer">
    <img src="http://upload.wikimedia.org/wikipedia/commons/d/d5/Blue_Circle_o.jpg">
    <img style="display:none;" src="http://i00.i.aliimg.com/img/pb/301/829/308/308829301_525.jpg">
</div>
<div class="myCareer">
    <img src="http://farm3.staticflickr.com/2226/1667080567_172c7871d3.jpg">
    <img style="display:none;" src="http://www.venatu.com/images/ge/purple-circle.png">
</div>

Jquery:

$('div').click(function(){
    $(this).find('img:hidden').addClass('tofadein');
    $(this).find('img:visible').addClass('tofadeout');
    $(this).find('img.tofadein').fadeIn();
    $(this).find('img.tofadeout').fadeOut();
    $(this).find('img').removeClass();  

    $(this).siblings('div').find('img').eq(0).fadeIn();
    $(this).siblings('div').find('img').eq(1).fadeOut();
    $(this).siblings('div').find('img').eq(2).fadeOut();
});
Was it helpful?

Solution

I think this fiddle accomplishes what you're trying to do:

JSFIDDLE

basically the key was to add an each function to do what you were already doing to every sibling. I also removed the div from the siblings function but only because it isn't necessary in the example. Its likely you may still need it in your actual code. Lastly, no .eq(2) exists. Guessing you were experimenting with that one.

heres the new js

$('div').click(function(){
    $(this).find('img:hidden').addClass('tofadein');
    $(this).find('img:visible').addClass('tofadeout');
    $(this).find('img.tofadein').fadeIn();
    $(this).find('img.tofadeout').fadeOut();
    $(this).find('img').removeClass('tofadein').removeClass('tofadeout');

    $(this).siblings().each(function(){
        $(this).find('img').eq(0).fadeIn();
        $(this).find('img').eq(1).fadeOut();
    });
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top