Lasse Edsvik
Lasse Edsvik

Reputation: 9298

Change image src based on style width + height

I have an asp.net mvc project, and a function that streams out an image based on url parameters. like: /Image/40/100/50 streams out image with ImageID 40, 100px wide and 50px high.

So is there a way to change:

<img class="image" src="/Content/View?fileID=31" style="width: 500px; height: 100px; " />

To:

<img class="image" src="/Image/31/500/100" style="width: 500px; height: 100px; " /> 

In some fancy way? /Lasse

Upvotes: 1

Views: 598

Answers (2)

Blazemonger
Blazemonger

Reputation: 93003

How about this:

$('img').each(function() {
    var $this = $(this),
        id = $this.attr('src').substr($this.attr('src').indexOf('=')+1),
        wid = $this.width(),
        hgt = $this.height();
    $this.attr('src','/Image/'+id+'/'+wid+'/'+hgt);
});

Upvotes: 1

Phil Klein
Phil Klein

Reputation: 7514

I'm not sure I understand why you're trying to do this, but something along the lines of the following should do the trick:

$("img[src^='/Content/View?fileID=']").each(function() {
    var img = $(this);
    var id = img.attr("src").substring(21);
    img.attr("src", "/Image/" + id + "/" + img.width().toString() + "/" + img.height().toString());
});

Link to example: http://jsfiddle.net/Cfdfp/2/

Also, if you're only applying the image class to img elements that require this transformation, you could simplify the selector above:

$(".image").each(function() {
    var img = $(this);
    var id = img.attr("src").substring(21);
    img.attr("src", "/Image/" + id + "/" + img.width().toString() + "/" + img.height().toString());
});

Link to example: http://jsfiddle.net/Cfdfp/1/

Upvotes: 3

Related Questions