Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript: get an image width and than set a class

I want to analyse every image of an article and set an class for all images smaller/equal than perhaps 400px (and another class for images bigger than 400px) so that I can give them a specific style.

In jQuery it would be perhaps something like this

$('div#content').find('img').each(function () {
    var $this = $(this), width = $this.width();
     if (width <= 400) {
     $this.addClass('small_img');
}

var $this = $(this), width = $this.width();
    if (width > 400) {
    $this.addClass('large_img');
}       
}); 

But I need it to be in pure Javascript. As a stupid Journalist and Webdesigner I don't get it... If you could help me, I would be very thankful.

like image 398
Karim Bouchouchi Avatar asked Sep 22 '26 22:09

Karim Bouchouchi


2 Answers

You mean something FAST and short like this?

window.onload = function() {
   var n=document.getElementById('content').getElementsByTagName('img'), 
       i=n.length;
   while(i--){
       n[i].className = n[i].clientWidth > 400 ? 'large_img' : 'small_img' ;
   }
};

See this fiddle for working example.

Also read this question on SO for selecting a method to fetch the (computed) width.

like image 88
GitaarLAB Avatar answered Sep 25 '26 13:09

GitaarLAB


window.onload = function() {
   var content = document.getElementById('content');
   if (content) {
       var img = content.getElementsByTagName('img');
       for (var i = 0, count = img.length; i < count; i++) {
            if (img[i].offsetWidth <= 400) {
                img[i].className += ' small_img';
            } else {
                img[i].className += ' large_img';
            }
       }
   }
};
like image 43
Sergii Stotskyi Avatar answered Sep 25 '26 12:09

Sergii Stotskyi



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!