I have an element inside an <iframe>
I'd like to activate using a link outside the <iframe>
.
Example:
<iframe src="iframe.html" id="iframe">
*inside the iframe*
<div id="activate" class="activate">
</iframe>
<a href="#activate" target="iframe">Link</a>
I thought this would work but obviously does nothing because I'm stupid. Any ideas?
Approach 1: For adding additional div's in an iframe, you need to use a wrapper div, that wraps the contents of your intended div and the iframe into one unit. This way you can display the contents of your div along with the iframe embedding to the document/webpage.
Getting the element in IframegetElementById() method by passing iframe id as an argument. const iframe = document. getElementById("myIframe"); Now, it has and contentWindow property which returns the document object by using that we can access the elements from an Iframe.
We can use inline CSS for the iframe by using CSS inside the iframe tag.
You can embed an iframe in a page that is inside another iframe on another web page. When you set the target attribute to _parent, the link will open in the web page that is holding the iframe. In most situations with iframes, this target will open links in the same way that the _parent target does.
Framed page (test.html
):
....... lots of content ....
<div id="activate">Inside frame</div>
Page containing the frame (page-containing-frame.html
):
<iframe src="test.html" name="target-iframe"></iframe>
<a href="test.html#activate"
target="target-iframe"
onclick="frames['target-iframe'].document.getElementById('activate')
.scrollIntoView();return false">Click</a>
^ That's the link. I've split up code over multiple lines for visibility
name
attrbute with the value of target-iframe
(obviously, you can choose any desired value).The link contains three attributes, each supporting two methods to scroll to a link in the frame:
target="target-iframe"
and href="test.html#activate"
href
attribute must be the path of the frame, postfixed by the anchor, eg test.hrml#activate
. This method will cause the framed page to reload. Also, if the anchor is already at #activate
, this method will not work any more.frames
object (by name, NOT by id, target-iframe
). Then, the anchor is selected (document.getElementById('activate')
.scrollIntoView
method is used to move the element inside the viewport.onclick
method ends with return false
, so that the default behaviour (ie following the link, causing a page refresh), does not happen.Your current code did not work, because of the missing name
attribute (target="..."
cannot match IDs, only names). Also, #activate
is parsed in the context of the current page, so, the link points to page-containing-frame.html
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With