Created
November 27, 2014 18:03
-
-
Save jeffkreeftmeijer/8e9381de6ac141f4fd6f to your computer and use it in GitHub Desktop.
Anchors in iframes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<style> | |
a{ | |
display: block; | |
margin: 2em 1em; | |
} | |
</style> | |
</head> | |
<body> | |
<a name="anchor-1" href="#anchor-1">Anchor #1</a> | |
<a name="anchor-2" href="#anchor-2">Anchor #2</a> | |
<a name="anchor-3" href="#anchor-3">Anchor #3</a> | |
<a name="anchor-4" href="#anchor-4">Anchor #4</a> | |
<a name="anchor-5" href="#anchor-5">Anchor #5</a> | |
<script src="http://zeptojs.com/zepto.min.js"></script> | |
<script> | |
window.addEventListener('message', function(event) { | |
if(anchor = event.data['findElement']) { | |
element = $('[name="' + anchor + '"]') | |
window.parent.postMessage({"offset": element.offset().top}, "*") | |
} | |
}) | |
$(document).ready(function(){ | |
window.parent.postMessage("ready", "*") | |
$('a').click(function(){ | |
event.preventDefault() | |
window.parent.postMessage({"setAnchor": $(this).attr('name')}, "*") | |
}) | |
}) | |
</script> | |
</body> | |
</html> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<html> | |
<head> | |
<style> | |
iframe{ | |
width: 100%; | |
border: 1px solid #888; | |
height: 290px; | |
margin: 1em 0; | |
overflow: hidden; | |
} | |
</style> | |
</head | |
<body> | |
<iframe src="frame.html"></iframe> | |
<script src="http://zeptojs.com/zepto.min.js"></script> | |
<script> | |
window.addEventListener('message', function(event) { | |
if(event.data == 'ready') { | |
sendHash() | |
} | |
if(anchor= event.data['setAnchor']) { | |
window.location.href = '#' + anchor | |
} | |
if(offset = event.data['offset']) { | |
window.scrollTo(0, $('iframe').offset().top + offset) | |
} | |
}) | |
sendHash = function(){ | |
hash = window.location.hash.substring(1) | |
$('iframe')[0].contentWindow.postMessage({"findElement": hash}, '*') | |
} | |
$(window).on('hashchange', sendHash) | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment