Pull to refresh

Навигация на сайте с помощью стрелок на клавиатуре

При создании больших проектов нужно уделять особое внимание навигации: она должна быть не громоздкой, но удобной. Клавиатурная навигация клавишами ← и →, удерживая Ctrl, подходит лучше всего. Попытаюсь объяснить, как это сделать, на примере моего проекта Zelebober.Dictionary.

image


Нужно было сделать навигацию по терминам (по дате добавления; все термины на сайте пронумерованы), так как переходить постоянно к списку терминов неудобно. Конечно, проще всего было бы добавить ссылку на следующий термин и забыть, но для нас этого мало.

Для начала прикрутим библиотеку jQuery (скачать). После прикручиваем скрипт навигации при помощи стрелок:

document.onkeydown = NavigateThrough;

var focusInInput = false;

if (document.getElementsByTagName)
    onload = function () {
        var e, i = 0;
        while (e = document.getElementsByTagName('INPUT')[i++]) {
            if (e.type == 'text' || e.type == 'search') e.onfocus = function () {focusInInput = true};
            if (e.type == 'text' || e.type == 'search') e.onblur = function () {focusInInput = false};
        }
        i = 0;
        while (e = document.getElementsByTagName('TEXTAREA')[i++]) {
            e.onfocus = function () {focusInInput = true};
            e.onblur = function () {focusInInput = false};
        }
    };

function NavigateThrough (event) {
	if (!document.getElementById) return;

	if (window.event) event = window.event;

	if ((event.ctrlKey || event.altKey) && !focusInInput){
		var link = null;
		var href = null;
		switch (event.keyCode ? event.keyCode : event.which ? event.which : null){
			case 0x25:
				link = document.getElementById ('NextLink');
				break;
			case 0x27:
				link = document.getElementById ('PrevLink');
				break;
			case 0x26:
				link = document.getElementById ('UpLink');
				break;
			case 0x28:
				link = document.getElementById ('DownLink');
				break;
			case 0x24:
				href = '/';
				break;
		}

		if (link && link.href) document.location = link.href;
		if (href) document.location = href;
	}			
}

jQuery(function(){
  if(jQuery('.howcr').size() > 0){
    if(navigator.userAgent.toLowerCase().indexOf("mac os x 10_7")!=-1){
      jQuery('.howcr').html('Alt');
    }
  }
}); 


Почти закончили. Осталось прикрутить к странице ссылки на предыдущий и следующий термин. Для удобства, разместим между тегами head.
<link rel="next" href="ссылка на следующий термин" id="PrevLink" />
<link rel="prev" href="ссылка на предыдущий термин" id="NextLink" />


Получилось круто. В действии можно посмотреть тут: dictionary.zelebober.com/dictionary/word/1
Tags:
Hubs:
You can’t comment this publication because its author is not yet a full member of the community. You will be able to contact the author only after he or she has been invited by someone in the community. Until then, author’s username will be hidden by an alias.