Pregunta

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?

¿Fue útil?

Solución

Manually select the correct anchor:

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

Otros consejos

When your click handler runs, the new target is not set yet, it will happen afterwards. That is why the TOC always positions itself next to the previous target (working fine after two clicks on the same link).

You could either use setTimeout() to delay execution of the TOC placement, or listen to the onhashchange event that is fired when the browser sets the new target. Or you can simply give up the :target approach and locate the right anchor yourself, something like:

function foo() {
     //hash will be something like #top
     var hash = this.hash;

     //wait, it looks like an ID selector :)
     jQuery(hash).after(jQuery('.cb-toc'));
}

jsFiddle Demo

Some work might need to be done, so the hash variable always holds the right value in every browser (#whatever), so this example is not production-ready code, just an illustration.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top