Create a gist now

Instantly share code, notes, and snippets.

What would you like to do?
Anchors in iframes
<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>
<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