I'm writing a small documentation, html being like:
<dl class="commands">
<dt id="commandA">Command A</dt>
<dd class="description">This command makes you happy.</dd>
<dt id="commandB">Command B</dt>
<dd class="description">This command makes you even happier.</dd>
</dl>
I thought it would be nice if accessing mydoc.html#commandA
highlights where the description for command A
is written, and wrote the following JavaScript:
(function(){
window.addEventListener('load', emphCmd);
function emphCmd(){
var loc = window.location.href;
if (/\.html#.*$/.test(loc)){
var cmd = loc.split("#")[1]; // "commandA" for mydoc.html#commandA
var cmdElm = document.getElementById(cmd);
if (cmdElm !== null){ // if element with that id is found,
cmdElm.style.backgroundColor = "#eeeeaa"; // highlight its background.
}
}
}
})();
This works, but only when the page is loaded (well, of course. I said do this on load
). The cases where this script does nothing includes : i) when I manually add #commandA
to the address bar in the browser and press Enter (without F5 --- reloading) ii) Jumping within page with <a>
tag.
I want it to be highlighted in either case. For the <a href="#commandA">
, I could probablyanchor.addEventListener('click',emphCmd)
, although that does not seem very neat.
Is there an event for these "jumping within page"? If not, what are the good ways to achieve this effect?