Responsive design with multiple images

I am working on a 1 page website. To keep the site responsive I am using media queries with images with different dimensions e.a. home1600.jpg, home1024.jpg, home768.jpg etc (the trailing numbers are the different widths). when a certain link is clicked the right photo should fade in. To accomplish that each link has a class corresponding with the first part of the image names e.a. home, titles, contact etc.

The links look like this:


<li><a href="#" class="home">Home</a></li>
<li><a href="#" class="titles">Titles</a></li>
........
<li><a href="#" class="contact">Contact</a></li>

I have the following function to make this happen:


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

What should I change in this line:

$('#background').css('background-image', 'url(page_backgrounds/'+img_name+'.jpg)');

To take of the trailing numbers e.a. 1600, 1024 etc. So when the link home is clicked depending on the device width the right home photo will fade in!

Thank you in advance!

Hey donboe,

I would just add a function that grabbed the present window size and returned a value which you could act on:

function getResolution(){
  if ($(window).width() < 300){
    return "_small";
  } else if ($(window).width() >= 300 && $(window).width() < 900) {
    return "_medium";
  } else {
    return "_large";
  }
}

$('#background').css('background-image', 'url(page_backgrounds/' + img_name + getResolution() + '.jpg)');

Something like that maybe?

Hi Pullo thank you for the response. So the image names need to be home_small.jpg, home_medium.jpg, home_large.jpg?

Well you can name them as you wish, but if you were using my suggestion, then yes.

Hi Pullo. That works great! Thank you so much.