1

I would like to hide element with class="wp-caption-text" if image size is <= 300

<div id="attachment_65209" style="width: 230px">
 <a href="#" rel="lightbox[70848]">
  <img src="/LCP-2015-05-31-s1.jpg" width="220" height="269">
 </a>
 <p class="wp-caption-text">Sen. Charles Schwertner • District 5</p>
</div>

So far i tried using the following but no luck:

<script>
jQuery(window).on('resize load', function () {
 jQuery('.wp-caption-text').each(function(i, el){
  var section = jQuery('.wp-caption-text');
  var width = section.width();
  if (width <= 300) {
   section.attr('class', 'caption-none');
  }
 })
})
</script>
<style>.caption-none{display:none;}</style>

Any suggesstions?

choche7
  • 59
  • 1
  • 2
  • 9

3 Answers3

1

You can use .filter() to filter out the element and then use addClass() to add the class

jQuery(window).on('resize load', function() {

    //Filter elements having width < 300
    jQuery('.wp-caption-text').filter(function(i, el) {
        return $(this).width() <= 300;
    }).addClass('caption-none'); //Add the required class
})
Satpal
  • 132,252
  • 13
  • 159
  • 168
0

Try this:

jQuery('.wp-caption-text').each(function(i, el){
    if (jQuery(this).width() <= 300) {
        jQuery(this).addClass('caption-none');
    }
});
lmgonzalves
  • 6,518
  • 3
  • 22
  • 41
  • 1
    Thanks! One thing i noticed is that is working properly when viewing single post (http://communityimpact.com/updates-from-your-state-legislators-round-rock-pflugerville-hutto-june-2015/), BUT since my home page (http://communityimpact.com/) is using infinite scroll...when you reach to that post, the caption still showing up. Any ideas? – choche7 Jun 16 '15 at 20:37
0

You're taking the width of an array of elements. You'll need to apply it to each:

var section = jQuery(this);
var width = section.width();
isherwood
  • 58,414
  • 16
  • 114
  • 157