Search code examples
htmlanchor

Question mark '?' in anchor link


I have jsfiddle here to illustrate my question.

https://jsfiddle.net/morettmt/psh674k7/69/

I have a nav with anchor links to blocks in the page (it's not working perfect, but that’s not the question).

This is actual being used in a WordPress site where the block and the links are created by a content manager in the backend.

My problem is the link doesn't work if it has characters like question marks '?' in it.

Why does this not work if a question mark is in the link.

.block{
    background: #ddd;
    height: 300px;
    margin: 0 0 10px 0;
    padding: 10px;
}

Solution

  • To make the link work with the script you would need to escape the question mark so that it works as a selector:

    <a href="#three\?" class="js-sticky-link">Three?</a>
    

    However, that makes it fail if it falls back to using the native bookmarks. For that to work you would URL encode the question mark as %3f:

    <a href="#three%3f" class="js-sticky-link">Three?</a>
    

    Then to make the script work it should convert the URL encoded bookmark to the escaped selector:

    $('html, body').animate({
      'scrollTop': $($(this).attr('href').replace(/%3f/ig, '\\?')).offset().top-navHeight
    }, 1000);
    

    Here is a fiddle where it is implemented. I also added a link for turning the animation on and off so that you can test the fallback behaviour: https://jsfiddle.net/Guffa/psh674k7/83/

    To make it work for any character you would use the decodeURIComponent method to URL decode the string, then escape any characters that needs to be escaped to make it work in the selector, as shown in this question.