hide element based on width

67 Views Asked by At

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?

3

There are 3 best solutions below

1
On BEST ANSWER

Try this:

jQuery('.wp-caption-text').each(function(i, el){
    if (jQuery(this).width() <= 300) {
        jQuery(this).addClass('caption-none');
    }
});
0
On

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
})
0
On

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();