Search code examples
jqueryanchordom-traversal

jQuery to move a box adjacent to the current target anchor position


On this page > http://canvas.clickbump.com/example/

I've got a floating "Table of Contents" box which has hyperlinks that target a couple of hidden anchor elements on the page:

<a id="anchor1">This is anchor 1</a>

And

<a id="anchor2">This is anchor 2</a>

The markup of the box:

<details class="cb-toc" open="open">
    <summary>Table of Contents</summary>
    <ol>
        <li><a href="#top">GoTo Top</a></li>
        <li><a href="#anchor1">GoTo Anchor 1</a></li>
        <li><a href="#anchor2">GoTo Anchor 2</a></li>
    </ol>
</details>

I'm trying to use the jQuery script below in order to bind the clicks on the TOC's links so that it moves the floating box to the position adjacent to the target anchor. However, its hit or miss. Takes two clicks on the anchor to move the box to the proper position.

Here's the jQuery I'm using:

jQuery('.cb-toc a').on('click',foo);
function foo(){
    jQuery('a:target').after(jQuery('.cb-toc'));
}

Any ideas what can do to get it to move the box to the proper position on the first click every time?


Solution

  • Manually select the correct anchor:

    jQuery('.cb-toc a').click(function(e){
        var str = jQuery(this).attr('href');
        jQuery(str).after(jQuery('.cb-toc'));
    }