Evster
Evster

Reputation: 2552

jQuery - enclose image in a div with a dynamically set width

EDIT 1/27/12 11:32am - I believe I have fixed all issues associated with this script. I need to apply a CSS class to each image I want to resize depending on if I want to float it left, right or have it centered, but I can live with that. See my latest explanation and demo at http://evanwebdesign.com/responsive-web-design/example5.html

Edit 1/27/12 10:50am - There is still a problem with this script. See my comments below. Working on a fix.

EDIT 1/27/12 9:00am: I now have this problem nearly complete. See my example at http://www.evanwebdesign.com/responsive-web-design/example3.html and compare with my original examples

I currently have an example of a responsive image that adjusts depending on the width of the browser window posted at http://evanwebdesign.com/responsive-web-design/example.html.

EDIT 1/16/12: I have made a more elaborate example that (hopefully) makes my question easier to understand at http://evanwebdesign.com/responsive-web-design/example2.html

But suppose I have multiple images within my #content div? And suppose they're all different widths? I don't want to manually calculate width values and create enclosing divs with custom classes for all of my images!

Instead I want to write a jQuery script that will do the following:

The goal is to dynamically create the .home_photo div for each image within the #content div. I don't care if the CSS is written inline, as the markup will never appear in the HTML.

Please let me know if this question is clear, or if there is anything else I can do to better explain myself. I know there are a lot of steps involved with this question.

Thanks in advance to everyone for your help!

Upvotes: 1

Views: 2962

Answers (2)

joel.d
joel.d

Reputation: 1631

As I understand it, you want to wrap each image in a div that will be sized based on the image's native size relative to the main #content div.

This should do the trick:

$(document).ready(function()   {
   var contentWidth = $('#content').width();
   $("#container img").each(function(){
        var ratio = $(this).width()/contentWidth;
        $(this).wrap("<div style='width:"+ratio+"'></div>");
});

You mentioned window.load - $(document).ready is a better version to use with jQuery because it executes immediately after the DOM is loaded, rather than waiting for all resources (including images for example) on the page to load.

Upvotes: 1

alex
alex

Reputation: 580

I think you can do this with css only

<style>
   .home_photo img
   {
        width:900px;
   }
</style>

Let me know if I misunderstood smthing

EDIT

I think this will do the trick

$(function(){
   $(window).resize(function(){
       $("#container img").each(function(){
        if($("#content").width() < $(this).width())
        {
            $(this).width($("#content").width());
        }
        });
   });
});

Upvotes: 0

Related Questions