Created
April 16, 2014 03:33
-
-
Save shiawuen/10803415 to your computer and use it in GitHub Desktop.
Scroll hash change
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
<!doctype html> | |
<html lang="en"> | |
<head> | |
<meta charset="UTF-8"> | |
<title>Document</title> | |
<style> | |
.block { | |
border: 1px solid #666; | |
box-shadow: 2px 2px 2px #333; | |
background: #f1f1f1; | |
height: 979px; | |
padding: 100px; | |
font-size: 20px; | |
color: #333; | |
max-height: 100%; | |
text-align: center; | |
} | |
.block:nth-child(1) { background-color: red; } | |
.block:nth-child(2) { background-color: green; } | |
.block:nth-child(3) { background-color: blue; } | |
</style> | |
</head> | |
<body> | |
<div class="container"> | |
<div class="block" id="block-1" data-program="block-1"> | |
<!-- <img src="img/Chrysanthemum.jpg"> --> | |
</div> | |
<div class="block" id="block-2" data-program="block-2"> | |
<!-- <img src="img/Desert.jpg"> --> | |
</div> | |
<div class="block" id="block-3" data-program="block-3"> | |
<!-- <img src="img/Jellyfish.jpg"> --> | |
</div> | |
</div> | |
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script> | |
<script> | |
(function(){ | |
// Since the sizes are fixed, | |
// you don't need to read the DOM always | |
// | |
var programs = $.map($('.block'), function (el) { | |
var $el = $(el); | |
var pos = $el.position(); | |
return { | |
y1: pos.top - 100, | |
y2: pos.top - 100 + $el.height(), | |
hash: $el.attr('data-program') | |
}; | |
}); | |
var top = null; | |
var changed = false; | |
var currentHash = null; | |
$(window).scroll(function () { | |
var newTop = $(document).scrollTop() | |
changed = newTop != top; | |
if (changed) | |
top = newTop; | |
}).scroll(); | |
// don't do DOM manipulation in scroll | |
// it will slow down the FPS a lot :) | |
// | |
// I pull it out into the step() so | |
// the checking only happen every 300ms | |
// which normal human wont notice :) | |
// | |
function step(){ | |
if (!changed) { return setTimeout(step, 200); } | |
var idx = programs.length; | |
var p; | |
while(p = programs[--idx]) { | |
if (p.y1 >= top || p.y2 <= top) { continue; } | |
if (currentHash == p.hash) { break; } | |
var scrollTop = $(document).scrollTop(); | |
window.location.hash = currentHash = p.hash; | |
// prevent browser to scroll | |
$(document).scrollTop(scrollTop); | |
} | |
setTimeout(step, 200); | |
} | |
setTimeout(step, 200); | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment