Return to Snippet

Revision: 37891
at December 19, 2010 10:12 by FatFolderDesigner


Initial Code
function init(){
	currentpos = 0
	h1tags = document.body.getElementsByTagName("h3");
	setInterval("locator()",500)
}
function locator(){
	checkpos=0
	while(h1tags[checkpos+1]!=undefined){
		if(h1tags[checkpos].offsetTop>(window.pageYOffset-(window.innerHeight)+h1tags[checkpos].clientHeight)){
			currentpos = checkpos
			checkpos = -3
		}
		checkpos = checkpos+1;
	}
}	
function keycatch(){
	keypress = event.keyCode
	switch(keypress){
		case 37: // Left
			if(currentpos!=0){
				currentpos = currentpos-1;
				h1tags[currentpos].scrollIntoView();
			}
			return false
			break;
		case 39: // Right
			if(h1tags[currentpos+1]!=undefined){
				currentpos = currentpos+1;
				h1tags[currentpos].scrollIntoView();
			}
			return false
			break;
	}
}

Initial URL
http://fatfolderdesign.com/141/code/javascript-navigation-part-deux

Initial Description
This fixes the downside of the original javascript keyboard navigation snippet I posted here  so that if you manually scroll past to a new chapter mark it will register that and keep track of your location better. The old code would ignore any scrolling you did, so if you read past a chapter and decided to skip one it would just take you to the top of the one you wanted to skip (I don't know if I'm explaining it behavior properly, theres a link in that post you can take to get to the example of the code set up and running on my site to see what I mean) and this one works properly

As with the first JavaScript Navigation snippet you can see it in action on my site and enjoy reading a classic in the process (it's even a different book this time).

As for implementation, the quick and dirty was in applying an onkeydown and an onload to the body tag, for the keycatch and init functions respectively. There are better ways but I was was more interested in testing the code rather than the implementation.

Initial Title
Better Javascript Keyboard Navigation

Initial Tags
javascript, navigation

Initial Language
JavaScript