-1

Is there a way to get every image on a page with the class of '.photo' and apply the class of '.vertical' to the article it's in if that photo's height is more than 450px tall? The reason I'm doing this is because I want tall photos to be less wide, therefore adding the class .vertical to style the article it's in to make that article 250px instead of the normal width of 500px...

Basically if a photo's 500px version is displayed on a page and the 500px photo has a height of more than 450px, it should resize the entire article it's in by adding the class .vertical to that article.

It sounds confusing but it's not once you understand it. I'm new to this so codes are appreciated, I have no clue what to do.

5 Answers5

4

Yes, there is.

First get the image height. How to get image size (height & width) using javascript?

Then use .addClass() to add a class if the height meets your requirements.

Community
  • 1
  • 1
sachleen
  • 30,730
  • 8
  • 78
  • 73
  • 4
    I could, but you should try to do it yourself first, then update your question with the code you're working on if you still need help. jsbin.com is a good place to play around with stuff. – sachleen Sep 11 '12 at 01:07
0

Try:

$('img.photo').each(function(){
    if($(this).height() > 450)
        $(this).closest('article').addClass('vertical');
});

Updated to add class to parent article. Change selector article as needed.

iambriansreed
  • 21,935
  • 6
  • 63
  • 79
0

Try this:

$(".photo").each(function(){
  var el = $(this);
  if (el.height() > 450)
    el.addClass("vertical");
});
badunk
  • 4,310
  • 5
  • 27
  • 47
0

Something like:

$(".photo").each(function(i) { 
  if ($(i).height() >450) {
     $(i).addClass('yourclass');
  }
});
firestream
  • 400
  • 2
  • 9
0

Hopefully this will get you started:

$('img.photo').each(function(index) {
    var height = $(this).height();
    if (height > 450) {
        $(this).parent().addClass('vertical');
    }
});

EDIT:

Regarding adding the .vertical class to the article that contains the image, that depends on your markup. @anonymous had one possible idea by finding the closest element with the class of .article. If the direct parent is the article that contains the image you could also use parent as in my edited code above.

davidethell
  • 11,708
  • 6
  • 43
  • 63
  • Please check out the edited version of my post, I don't know how to modify your code, I wrote what I needed wrongly. – James Charless Dickinson Sep 11 '12 at 01:15
  • I edited the code. Without seeing your HTML it's hard to say exactly what you need, but either what I have or what @anonymous has will get you headed in the right direction. You should edit your post to include the content in question. – davidethell Sep 11 '12 at 18:32