Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery get height & width

I made an if function to check if the width is < 100px. For some reason it hides everything. Anyone know why?

$(document).ready(function() {
var pic = $(".pic");

// need to remove these in of case img-element has set width and height
$(".pic").each(function() {
    var $this = $(this);
    $this.removeAttr("width"); 
    $this.removeAttr("height");

    var pic_real_width = $this.width();
    var pic_real_height = $this.height();
    if(pic_real_width<100){
    $(this).css("display","none");
    }
    });

 });
like image 787
Carvefx Avatar asked Dec 18 '25 22:12

Carvefx


2 Answers

You're using pic when you should be using $(this):

$(".pic").each(function() {
    var $this = $(this);
    $this.removeAttr("width"); 
    $this.removeAttr("height");

    var pic_real_width = $this.width();
    var pic_real_height = $this.height();
    alert(pic_real_width);
     });

You should also watch for images that are resized with CSS.

Instead of

    $this.removeAttr("width"); 
    $this.removeAttr("height");

try

$this.css({width: 'auto', height: 'auto'});
like image 184
Greg Avatar answered Dec 20 '25 13:12

Greg


Try this:

$(document).ready(function() {
    $(".pic").each(function() {
        var pic = $( this );
        pic.removeAttr("width"); 
        pic.removeAttr("height");

        var pic_real_width = pic.width();
        var pic_real_height = pic.height();
        alert(pic_real_width);
    });
});
like image 44
Jan Hančič Avatar answered Dec 20 '25 13:12

Jan Hančič



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!