David Coggins
David Coggins

Reputation: 841

jquery to apply a css class to an image based on its width

I have a div that is 770px wide. Due to surrounding elements I need to have the image within the div float left. I need to center the images that are less then 770px wide. Some image's are only 300px wide so stretching and cropping them are out of the question.

Is it possible to apply a class to all slider images that relates back to a jquery script that says if original image width is less then 770px then apply this css class to it. Then that class would center them image.

This seems like an easy fix but I cant wrap my head completely around it.

Here is a jsfiddle where im working.

would the toggle class work here? Just not sure how.

$(element).toggleClass("A B");

Any help or direction would be greatly appreciated.

Upvotes: 1

Views: 116

Answers (3)

maxinacube
maxinacube

Reputation: 661

Your fiddle is kind of a mess, so many scripts in different places. So I can't see exactly where your code for the Flexslider is, but the good news is that we should be able to figure this out without that :)

Flexslider has some pretty great built in functionality, including callbacks. Basically, you'll want to add something like this to the flexslider call:

$('#property-detail-flexslider').flexslider({
 after: function(){
  var current_img = $('.flex-active-slide img');
  if ( current_img.width() < 770 ) {
   current_img.addClass('center-img');
  }
 }
});

Upvotes: 1

jlzavitz
jlzavitz

Reputation: 11

If the containing container is 770, and you want anything 770+ to fill the container, then put a max width on the image, and center the image within. I don't see why you need to float left if you want it to be either centered or full

Upvotes: 0

weaknespase
weaknespase

Reputation: 1034

Temporarily free img tag from size limits, check its offsetWidth and then make decision about class. offsetWidth contain actual tag(block) width in pixels.

Upvotes: 0

Related Questions