tags:

views:

30

answers:

1

I was curious if it was possible to look at an images width, and if the width is less than X number, then it would get a certain class.

Essentially I want to specify three classes for images like so:

  • If width is less than 100px then the image itself will have the class .small
  • If width is less than 400px then the image itself will get the class .medium
  • If width is less than 600px then the image itself will get the class .large

.. etc If I need to add more sizes and classes

Is this possible?

+4  A: 
var img = $("#myImage");
var width = img.width();
if (width < 100)
    img.addClass("small");
else if (width < 400)
    img.addClass("medium");
else if (width < 600)
    img.addClass("large");

Untested, but that looks about right.

Also, if you wanted to apply these rules to all images in your document, or at least all images in a specific container, you could:

$("#divWithImages img").each(function(i, el)
{
    var img = $(el);
    var width = img.width();
    if (width < 100)
        img.addClass("small");
    else if (width < 400)
        img.addClass("medium");
    else if (width < 600)
        img.addClass("large");
});
Samuel Meacham
Actually I cant seem to get this to work.. hmm. Any ideas?
Bruno
@Bruno - why not?.. can you add some code on your post above...
Reigel
It works great, I just tested it. Note the selector: `$("#divWithImages img").each(function(i, el)`. This would apply your logic to all images that are inside of a div with id "divWithImages". Are you sure you have the selector right for your document setup?
Samuel Meacham
Here's the working example: http://jsbin.com/ukepe/edit
Samuel Meacham
Looks like I got a problem on my end... Not quite sure what is is though.. Thanks!
Bruno