getElementById attr image + jpg

I have a menu. Each anchor has it’s own class e.a. soup, salads, appetizers etc. I furthermore have a folder with different photo having the same name as the classes of the anchors e.a. soup.jpg, salads.jpg, appetizers.jpg etc. In my html I have a div holding a default background image. What I try to accomplish is that if a certain anchor is clicked the corresponding photo is loaded in div background. I have it working the following way:


  $('.menu a#soep').click(function(e) {
    e.preventDefault();
   $('.background').hide();
   $('.background').css('background-image', 'url(page_backgrounds/slide1.jpg)');
   $('.background').fadeIn(800);
  });

But then I need to have a separate function for each anchor. I am sure there must be a way to get all the classes of the anchors and connect the corresponding photo to that anchor, but I have no idea how. I have been looking into getElementById and attr. but haven’t found the right answer as yet

Any suggestions will be ore then welcome.

Depending on how you store the image in the div, you could select it by…

var img = $(‘.anchor img’).attr(‘src’);
$(‘.background’).css(‘background-image’, ‘url(’+img+‘)’;

Hi Patche. Thanks for the reply. The default image is stored the following way:


.background {
  width: 100%;
  height:100%;
  position: fixed;
  display:block;
  top: 0;
  left: 0;
  z-index: -999;
  background: url(../page_backgrounds/menu1600.jpg) no-repeat center center fixed;
  background-size: cover;
  -moz-background-size: cover;
  -webkit-background-size: cover;
  -o-background-size: cover;
  filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../page_backgrounds/index.jpg', sizingMethod='scale');
  -ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='../page_backgrounds/index.jpg', sizingMethod='scale')";
}

and this is an example of an anchor:


  <a href="#" class="soup">Soup</a>

hope this gives you some idea?

Oh… hmm, you could get the class name of the anchor and store your images as those names…

so your “soup” anchor would have an image soup.png… then you could do…


$('.menu a#soep').click(function(e) {
    e.preventDefault();
   var img_name = $(this).attr('class');
   $('.background').hide();
   $('.background').css('background-image', 'url(page_backgrounds/'+img_name+'.jpg)');
   $('.background').fadeIn(800);
  });

Something like the above? The img_name variable should contain the class name of the anchor being clicked (hopefully) but it may need some playing around with. Do you have the full html of your anchor list?

Works like a charm Patche. Thanks a lot :tup: