Trouble understanding $()

Trouble understanding $()

  1. $(document).ready(function() {
  2.     $('#bluebeans').click(function(){
  3.         $('.redbeanpic').fadeOut(200,function(){
  4.             // only then fade has finised, set index to 3
  5.             $('.bluebeanpic').css('z-index', '3');
  6.             $('.redbeanpic').css('z-index', '2').show();
  7.         });
  8.     });
  9.     $('#redbeans').click(function(){
  10.         $('.bluebeanpic').fadeOut(200,function(){
  11.             // only then fade has finised, set index to 3
  12.             $('.redbeanpic').css('z-index', '3');
  13.             $('.bluebeanpic').css('z-index', '2').show();
  14.         });
  15.     });
  16. });
So far so good, if I click on item with id redbeans, then bluebeanspic fades out and redbeanspic becomes visible from below in the z index stack. However what if I had three pictures instead of two?

I tried this (doesn't work):
  1. $(document).ready(function() {
  2. var $top = '.redbeanpic'
  3.     $('#bluebeans').click(function(){
  4.         $top.fadeOut(200,function(){
  5.             // only then fade has finised, set index to 3
  6.             $('.bluebeanpic').css('z-index', '3');
  7.             $top.css('z-index', '2').show();
  8. var $top = '.bluebeanpic';
  9.         });
  10.     });
  11.     $('#redbeans').click(function(){
  12.         $top.fadeOut(200,function(){
  13.             // only then fade has finised, set index to 3
  14.             $('.redbeanpic').css('z-index', '3');
  15.             $top.css('z-index', '2').show();
  16. var $top = '.redbeanpic';
  17.         });
  18.     });
  19.       $('#greenbeans').click(function(){
  20.         $top.fadeOut(200,function(){
  21.             // only then fade has finised, set index to 3
  22.             $('.greenbeanpic').css('z-index', '3');
  23.             $top.css('z-index', '2').show();
  24.             var $top = '.greenbeanpic';
  25.         });
  26.     });
  27. });