Search code examples
javascriptjqueryhtmlcssinternet-explorer-7

jQuery - Set CSS dimensions according to HTML attributes


As most of us know, there's a thing I like to call a bug in <IE7, where images don't resize when you put your dimensions only in the attributes. You need to set the CSS width and height as well. Now I've built a site without this in mind and I thought it could be solved with jQuery in a few lines. The problem is that I don't know the syntax at all and I need the solution fast. I'll dive into jQuery later, but now I need to fix it ASAP.

But please, if you write a script, comment it so I know which line does what. Thank you in advance.

Basically, what it does is scan every img tag on the site and set CSS dimensions according to the attributes of the tag.

What I tried was this:

  $(function(){
    $('img').each(function() {
        this.css("width":this.attr('width'),"height":this.attr('height'));
      });
});

Yet nothing happens.

EDIT: Fixed with help of Arun P Johny :)

$(function () {
    $('img').attr("style", function () {return "width:" + $(this).attr('width') + "px;height:" + $(this).attr('height') + "px;"});
});

Seems to work pretty well with wordpress :)


Solution

  • Inside the each callback this refers to the dom element not a jQuery wrapper object so it does not have methods like .attr().

    But the solution you are looking for is

    $(function () {
        $('img').css("width": function () {
            return $(this).attr('width')
        }, "height": function () {
            return $(this).attr('height')
        });
    });
    

    Demo: Fiddle