How Can I Target A Div Inside An Iframe?
I have an element inside an
Solution 1:
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
Explanation
- The frame has a
nameattrbute with the value oftarget-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"andhref="test.html#activate"This is the fallback method, in case of an error occurs, or if the user has disabled JavaScript. The target of the link is the frame, thehrefattribute must be the path of the frame, postfixed by the anchor, egtest.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.- This is the elegant solution, which shold not fail. The desired frame is accessed through the global
framesobject (by name, NOT by id,target-iframe). Then, the anchor is selected (document.getElementById('activate'). Finally, thescrollIntoViewmethod is used to move the element inside the viewport. Theonclickmethod ends withreturn 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.
Post a Comment for "How Can I Target A Div Inside An Iframe?"