How to target div inside an iframe?

I have an element inside an <iframe> that I would 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?

+6
source share
1 answer

Framed Page ( test.html ):

 ....... lots of content .... <div id="activate">Inside frame</div> 

The 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 the link. I've split up code over multiple lines for visibility 

Description

  • The frame has a name attrbute with a target-iframe value (obviously, you can choose any value you want).
  • The link contains three attributes, each of which supports two methods to scroll the link in the frame:

    • target="target-iframe" and href="test.html#activate"
      This is a backup method in case of an error or if the user has disabled JavaScript.
      The purpose of the link is a frame, the href attribute must be a frame contour fastened by an anchor, for example test.hrml#activate . This method will force the framed page to reload . Also, if the binding is already in #activate , this method will no longer work.
    • This is an elegant solution that will not fail. The required frame is accessed through the global frames object (by name, NOT by id, target-iframe ). An anchor is then selected ( document.getElementById('activate') .
      Finally, the scrollIntoView method scrollIntoView used to move an element inside the viewport.
      The onclick method ends with return false , so that the default behavior (i.e., after the link causing the page to refresh) does not occur.

Your current code does not work, because the missing attribute name ( target="..." cannot match identifiers, only names). In addition, #activate parsed in the context of the current page, so the link points to page-containing-frame.html .

+13
source

Source: https://habr.com/ru/post/903745/


All Articles