[UPDATE] I rewrote the code to match all the anchors that have an id, and simplified the comparison of the norm of the vectors in my sortByDistance
function.
Check my attempt on jsFiddle (the previous one was here ).
The javascript part :
// findPos : courtesy of @ppk - see http://www.quirksmode.org/js/findpos.html
var findPos = function(obj) {
var curleft = 0,
curtop = 0;
if (obj.offsetParent) {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
while ((obj = obj.offsetParent)) {
curleft += obj.offsetLeft;
curtop += obj.offsetTop;
}
}
return [curleft, curtop];
};
var findClosestAnchor = function (anchors) {
var sortByDistance = function(element1, element2) {
var pos1 = findPos( element1 ),
pos2 = findPos( element2 );
// vect1 & vect2 represent 2d vectors going from the top left extremity of each element to the point positionned at the scrolled offset of the window
var vect1 = [
window.scrollX - pos1[0],
window.scrollY - pos1[1]
],
vect2 = [
window.scrollX - pos2[0],
window.scrollY - pos2[1]
];
// we compare the length of the vectors using only the sum of their components squared
// no need to find the magnitude of each (this was inspired by Mageek’s answer)
var sqDist1 = vect1[0] * vect1[0] + vect1[1] * vect1[1],
sqDist2 = vect2[0] * vect2[0] + vect2[1] * vect2[1];
if ( sqDist1 < sqDist2 ) return -1;
else if ( sqDist1 > sqDist2 ) return 1;
else return 0;
};
// Convert the nodelist to an array, then returns the first item of the elements sorted by distance
return Array.prototype.slice.call( anchors ).sort( sortByDistance )[0];
};
You can retrieve and cache the anchors like so when the dom is ready : var anchors = document.body.querySelectorAll('a[id]');
I’ve not tested it on a smartphone yet but I don’t see any reasons why it wouldn’t work.
Here is why I used the var foo = function() {};
form (more javascript patterns).
The return Array.prototype.slice.call( anchors ).sort( sortByDistance )[0];
line is actually a bit tricky.
document.body.querySelectorAll('a['id']')
returns me a NodeList with all the anchors that have the attribute "id" in the body of the current page.
Sadly, a NodeList object does not have a "sort" method, and it is not possible to use the sort
method of the Array prototype, as it is with some other methods, such as filter or map (NodeList.prototype.sort = Array.prototype.sort
would have been really nice).
This article explains better that I could why I used Array.prototype.slice.call
to turn my NodeList into an array.
And finally, I used the Array.prototype.sort
method (along with a custom sortByDistance
function) to compare each element of the NodeList with each other, and I only return the first item, which is the closest one.
To find the position of the elements that use fixed positionning, it is possible to use this updated version of findPos
: http://www.greywyvern.com/?post=331.
My answer may not be the more efficient (drdigit’s must be more than mine) but I preferred simplicity over efficiency, and I think it’s the easiest one to maintain.
[YET ANOTHER UPDATE]
Here is a heavily modified version of findPos that works with webkit css columns (with no gaps):
// Also adapted from PPK - this guy is everywhere ! - check http://www.quirksmode.org/dom/getstyles.html
var getStyle = function(el,styleProp)
{
if (el.currentStyle)
var y = el.currentStyle[styleProp];
else if (window.getComputedStyle)
var y = document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp);
return y;
}
// findPos : original by @ppk - see http://www.quirksmode.org/js/findpos.html
// made recursive and transformed to returns the corect position when css columns are used
var findPos = function( obj, childCoords ) {
if ( typeof childCoords == 'undefined' ) {
childCoords = [0, 0];
}
var parentColumnWidth,
parentHeight;
var curleft, curtop;
if( obj.offsetParent && ( parentColumnWidth = parseInt( getStyle( obj.offsetParent, '-webkit-column-width' ) ) ) ) {
parentHeight = parseInt( getStyle( obj.offsetParent, 'height' ) );
curtop = obj.offsetTop;
column = Math.ceil( curtop / parentHeight );
curleft = ( ( column - 1 ) * parentColumnWidth ) + ( obj.offsetLeft % parentColumnWidth );
curtop %= parentHeight;
}
else {
curleft = obj.offsetLeft;
curtop = obj.offsetTop;
}
curleft += childCoords[0];
curtop += childCoords[1];
if( obj.offsetParent ) {
var coords = findPos( obj.offsetParent, [curleft, curtop] );
curleft = coords[0];
curtop = coords[1];
}
return [curleft, curtop];
}