This follows on from the thread I began here: http://stackoverflow.com/questions/3173073/capture-the-next-main-block-element-using-js
Later on new issues became apparent and I had 2 refine and add to what I had already, to cover these unforseen eventualities.
I have 2 questions:
Is the try catch block a sound idea?
Have I covered all possibilities here ('What else could go wrong?', he asked. 'You would be suprised!', they said.)?
var scrollToThenFlash = (function () { document.onclick = function () { /* Note: Using document.all throughout. Cross-browser-compatability is not an issue here */ var d = document, dael = d.activeElement;
function getElById(id) {
if (d.all[id] && d.all[id].id === id) /* Have we found the target el.id or an el with attr name===id? (document.all matches BOTH! id and name attributes) */
return d.all[id];
else for (var i = 1, L = d.all[id].length; i < L; i++) if (d.all[id][i].id === id) return d.all[id][i];
};
if (/* We've clicked on a hash URL? */ dael.href.indexOf('#') != -1 && /* Is the target #el.id on this pg or does this link take us elswhere? If true we override the default link action and find target el.id 'manually' */ getElById(dael.href.split('#')[1])) {
dael.style.background = '#ff9 !important';
dael.style.color = '#444 !important'; /* Target element */
obj_el = getElById(dael.href.split('#')[1]); /* Does the target element have any innerHTML? If not we can't hilite or scroll to it */
if (obj_el.innerHTML == '') obj_el.appendChild(d.createElement('center')).innerHTML = '<P>X<\/P>'; /* Find the next main block element below the target element (p, div, pre, h etc) so that we can hilite that too (unsure if my method is sound. Any suggestions please!). */
try {
function get_nextSibling(n) {
var x = n.nextSibling;
while ( /* Skip any whitespace or br */ x.nodeType != 1) {
x = x.nextSibling
};
return x;
};
obj_el2 = get_nextSibling(obj_el)
} catch (e) {
obj_el2 = d.all[obj_el.sourceIndex + 1]
}; /* Remember the 2 elements original colors */
obj_elbg = obj_el.style.background;
obj_elbg2 = obj_el2.style.background; /* Scroll to target element */
function findPos(obj) {
var curtop = 0;
if (obj.offsetParent) {
do {
curtop += obj.offsetTop
} while (obj = obj.offsetParent);
return [curtop]
};
};
scroll(0, findPos(obj_el)); /* Toggle obj_el and obj_el2 backgrounds */
function flash(rep, delay) {
for (var i = rep; i > 0; i--) {
setTimeout("obj_el.style.background='yellow !important';obj_el2.style.background='yellow !important';", delay * i * 2);
setTimeout("obj_el.style.background=obj_elbg;obj_el2.style.background=obj_elbg2;", delay * ((i * 2) + 1))
};
};
flash(7, 130); /* Override default action by returning false */
return false
} else { /* Allow default: We're leaving this page or duplicate ids were found or the link does not have a hash URL. */
return true
};
};
}); scrollToThenFlash();