Jump to content

Add class to parent div based on image being landscape or portrait


erme

Recommended Posts

I have a series of images in a div called .img_wrapper. I want to add a class to this div based on whether the image in the div is landscape or portrait.

 

This is what I have come up with but doesn't work:

 $(".img_wrapper").each(function(){    

    var img = $(".img_wrapper img");
    var div = $(".img_wrapper");

    if (img.height() < img.width()){
        div.addClass('landscape');
    } else {
        div.addClass('portrait');
    }

});

Note that you won't be able to access the <div> and <img> tags until the page fully loads. Is your code behind an "onload" event? Since you're using jQuery, perhaps the following will help:

http://api.jquery.com/ready/

Note that you won't be able to access the <div> and <img> tags until the page fully loads. Is your code behind an "onload" event? Since you're using jQuery, perhaps the following will help:

http://api.jquery.com/ready/

 

 

Yea its wrapped in $(document).ready(function()

Could you provide a little more information by what you mean by "it doesn't work"? Also, it might help to show more code. Are you importing a jQuery library?

 

For what it's worth, the following code works for me:

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
     $(".img_wrapper").each(function(){
          var img = $(".img_wrapper img");
          var div = $(".img_wrapper");

          if (img.height() < img.width()){
               div.addClass('landscape');
          } else {
               div.addClass('portrait');
          }
     });
});
</script>
</head>
 
<body>
<div class="img_wrapper"><img src="myImage.jpg" width="225" height="500" /></div>
</body>
</html>

Hi, just tried it. It takes the size of the first image in img_wrapper and applies the class to the rest of the img_wrapper divs. So if the first image is landscape, the rest will be landscape regardless of the image size.

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.