tags:

views:

331

answers:

2

I google it up but didn' find something like this.

I am having an iframe with 2 main attributes src=# and link=http://somesite.com

<iframe id="myiframe" src="#" link="https://somesite.com?id=x&amp;anotherid=y" style="position:absolute; left:0px; top:0px; width:99%; min-width:80%; height:99%; min-height:80%; padding:0px;"></iframe>

I load that iframe in HTML from some php script but i don't want to load the page thats why i used # as source, now when i click a button on the site it will load the iframe (if it was not loaded from a previous click), my temporary solution was:

<input type="button" value="load" onClick="var fr = document.getElementById('myiframe');if(fr.src.substr(-1)=='#'){fr.src=document.fr.getAttribute('link')};" />

Now I had a little time to implement the jQuery and I whant to know if there is some simple code in jQuery to copy from an attribute to another, or if there is a better solution to accomplish this.

something like this: $('#myiframe').attr('src', attr('link'));

i know the folowing will work

$('#myiframe').attr('src', attr('link'));

but i think is not to much to select the same element twice. (I am kind of an optimizer maniac :) )

or you think that I have to use a function:

$('#myiframe').attr('src', function(){
    ...
});

My question is what is the best way to achieve this. Thank you.

+1  A: 

If you don't want to select the element twice - cache it.

var $myiframe = $('#myiframe');
$myiframe.attr('src', $myiframe.attr('link'));

I don't think $('#myiframe').attr('src', attr('link')); will work.

You should be able to do it with a function as well:

$('#myiframe').attr('src', function () {
    return $(this).attr('link');
});

Also, as a side note - try to avoid using the onclick= attribute. Just bind yourself in jQuery to the click event like this:

$('input[type=button][value=load]').click(function () {
    // One of the solutions above
});
Emil Ivanov
+1  A: 

I doubt you can get more efficient than this:

var fr = $('#myiframe');
if (fr.attr('src').slice(-1) === '#') {
  fr.attr('src', fr.attr('link'));
}

Note: I used slice() instead of substr() because IE does not support negative start values.

brianpeiris