Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Responsive Overlay Image on smaller screens?

Hey everyone,

So I am trying to take the lightbox we created in this course and make the image that is selected responsive to screen size... The images I am using for my project with this are quite a bit larger than a tablet or mobile screen, but I'd like to get it to resize to the width of the browser window.

Thus far I've only been able to set a attribute to have a set width but that isn't exactly helpful, because then it's either too small for a PC browser window, or too big for a mobile window.

Any thoughts?

Here is my Javascript

// Problem: User when clicking on image goes to a dead end
// Solution: Create an overlay with the large image

var $overlay = $('<div id="overlay"></div>');
var $image = $("<img>");
var $caption = $("<p></p>");

// An image to overlay
$overlay.append($image);

// Caption add to overlay
$overlay.append($caption);

// Add overlay
$("body").append($overlay);

// Capture click event on link to image
$("#imageGallery a").click(function(event) {
  event.preventDefault();
  var imageLocation = $(this).attr("href");

  // Update overlay with the image linked in the link
  $image.attr("src", imageLocation);
  $image.attr("width", "700");  
  // Show the overlay
  $overlay.show();

    // Get child's alt attribute and set caption
  var captionText = $(this).children("img").attr("alt");
  $caption.text(captionText);
});

  // When overlay is clicked 
$overlay.click(function(){

  // Hide overlay
  $($overlay).hide();
});

1 Answer

Hi Adam, You can always use CSS to create responsive images. Do so by giving the images a width of 100% and a height: auto. To handle different screen sizes, use a media query.

Another approach would be to get the window size and set the image to that size For example

var $screenWidth = $( window ).width(); //gets viewport width

//your code

//set screenWidth to be image width
$image.css({
  maxWidth: $screenWidth + 'px'
});

If you take the JavaScript approach, you can use the resize() jQuery function to make the image responsive by updating the image width.

Hope that helps.

Thanks so much ! :D