I was building a page in a website. In that page I was loading a page inside an iframe. The page inside iframe had an anchor (http:/fellowtuts.com/test.html#specific_content) as well. When I used to click on the anchors within the iframe to reach the specific content section, it was working in firefox browser smoothly but working with a undesired behaviour in chrome and internet explorer browsers. In chrome, it was scrolling the parent window to top along with Iframe’s content.
Prevent anchor in an iframe from scrolling the parent window
So I applied a little jQuery to resolve the issue. I am explaining the same solution here so that it can help to others also.
These are the links in the iframe page which targets to a specific sections in the page.
1 2 3 | <p><a href="#section1" class="offsetLink">Go to Section I</a></p> <p><a href="#section2" class="offsetLink">Go to Section II</a></p> <p><a href="#section3" class="offsetLink">Go to Section III</a></p> |
For getting work the solution, we need to prevent default action of anchor tags and use the click event of anchor tags by which we can prevent anchor in iframe from scrolling the parent window.
We need to do 2 things here:
1. Include jQuery file
1 | <script type="text/javascript" src="../js/jquery-1.11.1.min.js"></script> |
2. include the below given code in your page.
1 2 3 4 5 6 7 8 9 10 | <script> jQuery(document).ready(function(){ jQuery('.offsetLink').click(function(){ hrf = jQuery(this).attr('href'); topPos = jQuery(hrf).offset().top; jQuery('html, body').scrollTop(topPos); return false; }); }); </script> |
In this code, we are binding anchor links to click event and taking their href attribute to get the offset of targeted section. Then move the body to that offset position. One important thing is that we are preventing the default action of anchor tag by returning false in end of the click function which prevent anchor in an iframe from scrolling the parent window.
Please be aware that the above steps should be included in iframe itself and I assume that iframe contents are coming from the same domain where the parent page resides.