Niklas Möller
Niklas Möller

Reputation: 115

Scroll parent frame to anchor in iframe

I'm new here ... hope I'm doing everything right ;-D

I've found a few topics with similar problems but they do not look like they want to reach what I want to reach.

I've got a website with a long content area, the website has scrollbars. Somewhere inside this content area is an iframe. This iframe implements a site with full height (a support board) and resizes the iframe when the contents height is changing - so the iframe has no scrollbars. Now what I want is: when I'm opening the website with i.e. http://www.mywebsite.com/#new I want the page to scroll down to the iframe but not only the begining of the iframe but the position where the anchor is placed inside this iframe.

So the iframe itself doesn't need to be scrolled (it's always 100% height) but the parent frame should be scrolled to the position where - inside of the iframe - the anchor is placed.

I really don't know how to solve this. Adding the anchor to the iframes url doesn't help and also just adding the anchor to the website url doesn't work. I'm sure I have to implement something with javascript or similar but don't know how! I'm able to modify the code of both - the website inside the iframe and the parent site!

//EDIT
Oh i forgot... I can't do it with an onClick-Action or a link attribute (that's what seams to be the solution in a related post) because it's not a jump inside the same page. The page is being reloaded and should jump to the anchor :-D So it has to work when I'm entering the URL on my own...
Hope you understand what I need!

//EDIT2 Possible frameworks:

Upvotes: 4

Views: 5570

Answers (1)

Sergio
Sergio

Reputation: 28837

Here is an answer that will put you "on the right way".

Assuming your iFrame is always in the same position inside your main page, what you need is to scroll the main page to this point: iframe y coordinate + anchor coordinate inside iFrame.

So I will call you anchor: <a name="anchor1">Here</a> and you iFrame: <iframe id ="myiFrame" ...

To get the iframe position in the page you can use $("#myiFrame").position().top and the anchor position inside the iFrame with $("#myiFrame").contents().find('a[name=anchor]').position().top.

So your script moght look like:

var y = $("#myiFrame").position().top + $("#myiFrame").contents().find('a[name=anchor]').position().top;
$(window).scrollTop(y)

Upvotes: 3

Related Questions