views:

29

answers:

2

Hi all. I have a page with an iframe. Inside the iframe is code (that I can't change) that sets location.hash to the id of an element in the iframe window.

This has the unwanted effect of scrolling my outermost browser window so that the top of the window touches the top of the iframe. This is quite annoying as I have a toolbar above the iframe that is vital to my app.

Is there any way of preventing the setting of location.hash affecting the scroll position of the main window?

Will preventDefault help me out here?

Thanks!

A: 

You can use:

event.preventDefault()

This will stop the default action of the element it is applied to.

https://developer.mozilla.org/en/DOM/event.preventDefault

matpol
Thanks - which event would I attach this to though? I've tried: window.onscroll = function(e){ e.preventDefault(); };in both the parent window and the iframe to no avail.
Ben Clayton
How does the iframe get called - I would try and set the preventdefault on the click event calling it if you can.
matpol
some internal code (not related to a click event) in the iframe calls location.hash = "#" + id. I can't stop it running that line or the code in the iframe will break..
Ben Clayton
+1  A: 

If preventDefault doesn't do what you want it to, you could do is dynamically move the location of the <a name='iframehash'> so that it's always at the top of the screen. That way, when the call to move to whatever hash it's going to gets called, nothing will actually move.

But if preventDefault() works, it's a much better solution.

Jamie Wong
Cheers Jamie. I've tried this one too. I've put an anchor at the top of the main html file, and dynamically set its name to the anchor used in the iframe and that didn't help either :-(
Ben Clayton