How to Change Iframe Src Without Reloading the Iframe

Is it possible to change the source of an iframe without page postback?

Using jquery.attr() method, you can change the src parameter.

$("#myifrm").attr("src","your url here");

To see a working sample, take a look at this:
http://jsfiddle.net/YCDtj/

Change iframe src without page update

Step 1: Use an ID for the iframe...

<iframe id="FrameId"></iframe>

Step 2: Update your buttons...

<button type="button" onclick="ChangeSource(1);">Change to video 1</button>

Step 3: Include this function...

function ChangeSource(Button){
if(Button==1){FrameId.src='URL 1';} else
if(Button==2){FrameId.src='URL 2';} else
if(Button==3){FrameId.src='URL 3';} else
if(Button==4){FrameId.src='URL 4';}
}

Can I change the iframe src according to the url?

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

Prevent iframe from reloading when changing the src attribute?

If your parent site is on the same domain as child sites (mypage.com) you can try this:
https://stackoverflow.com/a/45828201/10672983

If you have a cross-domain problems, you can try to simple messaging system parent-> child:

How to communicate between iframe and the parent site?

Parent:

 myIframe.contentWindow.postMessage('/page2', '*');

Child:

window.onmessage = function(e){
router.navigateByUrl(e.data)
};

Can I change iframe src without js or ID's?

You can use an html link outside of the iframe, and set the target to the name of the iframe.

See the w3schools Example Here

<iframe src="demo_iframe.htm" name="iframe_a"></iframe>
<p><a href="http://www.w3schools.com" target="iframe_a">W3Schools.com</a></p>

If the link is inside the iframe, you simply need to set target=_self on the link.

<a href="http://www.w3schools.com" target="_self">W3Schools.com</a></p>

Changing iframe src with JavaScript not working

src is an attribute you can access directly so instead of your line elem.setAttribute('src', newsrc); just use this:

elem.src = "http://www.youtube.com/embed/" + explosion[4] + "?autoplay=1";

Once you set the src there is no need to refresh the iframe, as setting the src will do that automatically. See What's the best way to reload / refresh an iframe using JavaScript?
for more info on reloading iframes. (Basically it points out that you can set the src of an iframe to itself to refresh the iframe).



Related Topics



Leave a reply



Submit