JQuery to move field near current target anchor location

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

I have a floating Table of Contents box that 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>

      

Window layout:

<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 am trying to use the jQuery script below to bind clicks to TOC links so that it moves the float to a position adjacent to the target anchor. However, his hit or miss. Makes two clicks on the anchor to move the box to the correct 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 be done to make it move the field to the desired position on the first click every time?

+3


source to share


2 answers


Manually select the correct anchor:



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

      

+2


source


When your click handler is running, the new target has not yet been set, this will happen later. This is why TOC always positions itself next to the previous target (works fine after two clicks on the same link).

You can use setTimeout()

posting TOC to delay execution, or listening for an event onhashchange

that fires when the browser sets a new target. Or you can just drop the approach :target

and find the correct 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

It might need some work to be done, so the variable hash

always contains the correct value in every browser ( #whatever

), so this example is not production-ready code, but just an illustration.

+2


source







All Articles