4

An iframe is found with some different pages forexample <iframe src="..."></iframe> in site.com/page1 and site.com/page2, I want to change the iframe src according to the url above, Can I do that, If I can how can I do that? Please help!

Note: the url is dynamic so I can't use if else condition

Thanks

Miheretab Alemu
  • 956
  • 2
  • 20
  • 43

2 Answers2

5

Yes.

The simplest solution is don't set the iframes src in the HTML, just declare the iframe tag and give it an id, say "myIframe".

Then just do some simple javascript.

var iframe = document.getElementById('myIframe');
if(window.location.href === SITE_1_URL){
   iframe.src = something;
} else {
   iframe.src = somethingElse;
}

Note the iframe doesn't load until its src property is set.

asutherland
  • 2,849
  • 4
  • 32
  • 50
  • Thanks But what I need is not only for two pages, but for many pages and I don't want to write if else because the url is dynamic – Miheretab Alemu Mar 07 '14 at 17:51
  • 2
    Well of course you can execute any logic you want based on the window.location. So if you have some function foo that takes the top level url and returns the appropriate iframe url for that top level page then you want you would just do iframe.src = foo(window.location.href); – asutherland Mar 07 '14 at 17:54
2

on page ready event you check the current url and set the iframe src attribute according see this link

Community
  • 1
  • 1
Sérgio S. Filho
  • 364
  • 1
  • 4
  • 13