Pregunta

I'm looking for the best way to have a class added to an img tag if the width of the image is smaller than the section element.

<section>
<img>
</section>

section {
   width:700px
}

I tried the following with no such luck:

var image = $('img');
var width = $('section').width();

if (width < 700) {
image.addClass('classname');

any help would be great guys :)

¿Fue útil?

Solución

As per my comment you are trying to add the class to "img" which is undefined. Either switch that out so you have

image.addClass('classname')

Or since it's a short selector just insert that

$('img').addClass('classname')

Also make sure that the jQuery call is being made within a $(document).ready(...) call

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top