Clicking on a link <a href="#f" rel="noopener noreferrer">Fa> should navigate to <section id="f" section> further down the page.
Clicking on a link <a href="#f" rel="noopener noreferrer">F</a> navigates to 404
Repo here: anchor-test
git clone
npm i
navigate to localhost:8080 and click link on top of page that reads "Go to F" (I'm not not _telling_ you to go to F 馃槃).
I've tried commenting out the catch-all route in index.js and that yields a console error:
Error: route '/f' did not match
So it looks like for some reason the # in the href is being disregarded?
Having the same issue.
<a href="#foo">Link</a> navigates to 404 instead of <p id="foo">Some content</p>
I use Browserify and Yo-yoify to bundle it all up. The bundle is connected to a Kirby backend.
Any tips?
Due to how choo handles hashes like any other route you'll have to capture the hash as a param and then choo will scroll to the element automatically.
app.route('/some-page', require('./views/page'))
app.route('/some-page/:anchor', require('./views/page')) // <- duplicate route for capturing anchors
The reason for this is so that you can mount a choo app not just on the website root but also under some path and then use hashes for routing. It's not pretty and I believe it has been up for discussion on how to mitigate this but idk if there's been any progress on that.
Usually what I do when linking to anchors on the same page is that I capture the click and manually scroll the element into view.
html`<a href="#foo" onclick=${onclick}>Go to foo</a>`
function onclick (event) {
var el = document.getElementById(event.target.hash.substr(1))
if (el) el.scrollIntoView({behavior: 'smooth', block: 'start'})
event.preventDefault()
}
Tack @tornqvist ! That was a huge help.
This worked great, except one small thing. The first time I click the link it jumps to the anchor tag rather than smoothly scrolling. After navigating to the new route (in my case localhost/#clients) clicking the link for the second time will produce a smooth scroll.
Seems like Choo didn't capture the hash in my case. I will have another look with fresh eyes tomorrow.
I have my anchor tag on the first page of my application and it's a non dynamic one so I made a workaround as follows:
<a href="/" onclick=${scroll}>Scroll down</a>
function scroll (event) {
var el = document.getElementById('scrollhere')
if (el) el.scrollIntoView({behavior: 'smooth', block: 'start'})
}
Basically never navigating away just running the scroll script on the link.
Don't forget to also call event.preventDefault() to stop choo from handling the click and issuing a rerender and trying to scroll the anchor into view. Might be what is causing the jump on first click.
If that is the case it'd be this line here that causes the jump: https://github.com/choojs/choo/blob/master/index.js#L104
I'll close this for now, let me know if you're still having any issues and I'll reopen it.