Replacing only part of an iframe src

I need to use javascript to change part of an iframe src, is there a way to change '500' to '800' in that iframe src? I tried the following code but it did not work. If anyone could help that'd be appreciated.

        function bigPhotosets() {
            $('iframe.photoset').each(function(){
                $(this).attr('src').replace('500','800');
                $(this).attr('width').replace('500','800');
            });
        }

        bigPhotosets();

Upvotes: 0

Views: 346

Answers (4)

Oscar
Oscar

Reputation: 130

Easiest way. Replace the old src with the same src but with 500 replaced with 800.

$(this).attr('src', $(this).attr('src').replace('500','800') );

In your link in the comments for the first answer it doesn't work because there is no 500 but a 600 in the iframe src.

Also note that you will have to take care of both the width attribute and the css width.

Which would give you

$(this).attr('width', 800);
$(this).css('width', 800);

After this the only thing left is to adjust the height of the iframe proportionally to how you changed the width. Which is oldHeight*800/500 (or in your actual case 800/600).

Upvotes: 0

CWSpear
CWSpear

Reputation: 3250

I believe SLaks' answer is correct. When I used his code in the console on your tumblr page, it changed the source correctly. The width didn't change however, and the height needs to be adjusted.

I pasted the following code into the console (on Chrome) on http://jtestblog1.tumblr.com/post/26387860417/aquaticwonder-dancing-alone-portraits-by-caiti and it worked as you say it needs to work.

function bigPhotosets() {
    $('iframe.photoset').each(function(){
        var newSrc = $(this).attr('src').replace('500','800');
        $(this).attr('src', newSrc).width(800).height(912);
    });
}

bigPhotosets();

I would be worried about another 500 existing in your URL. This would mess up the URL. If it's always going to be at the end of the URL you might want to use a regex that will only replace 500 if it only occurs at the end of the URL.

i.e. change the 3rd line to

var newSrc = $(this).attr('src').replace(/500$/,'800');

It will only work if 500 is at the end of the URL (which if the size is always going to be at the end of the URL, that's a good thing). On your tumblr, the size is at the end of the URL, so this regex works.

Upvotes: 0

davidbuzatto
davidbuzatto

Reputation: 9424

This code is just returnin the src attribute, replacing some text and doing nothing more. Try this:

$(this).attr('src', $(this).attr('src').replace('500','800') );

Upvotes: 0

SLaks
SLaks

Reputation: 887355

.replace() returns a new string, which you aren't doing anything with.

You need to set the src to this new string:

var newSrc = $(this).attr('src').replace('500','800');   
$(this).attr('src', newSrc);

There are also faster ways to do this.

Upvotes: 3

Related Questions