Page 1 of 1

Internal links in HTML object

Posted: Sun Jul 18, 2021 5:10 am
by nickrth
Hi Brains Trust,

I'm seeing some strange behaviour and I'm hoping someone can please spot what I'm doing wrong.

I have a HTML object on a form, and I want to have internal hyperlinks to jump you to different areas of the page (it's a big long document, so I'm effectively creating a table of contents). Near the top I have:

Code: Select all

<ol>
<li><a href="#planning">Planning</a></li>
<ul>
    <li><a href="#planningteam"> Organise your team</a></li>
    <li><a href="#planningequipment"> Organise your equipment</a></li>
</ul>
</ol>
Then in the relevant spots I have:

Code: Select all

<h1><a name="planning"></a>Planning</h1>
<h2><a name="planningteam"></a>Organise your team</h2>
But when I click the links, it takes me to the previous page in the browser, rather than jumping to the right spot on the current page.

Any ideas what I'm doing wrong? Thanks in advance.

Re: Internal links in HTML object

Posted: Sun Jul 18, 2021 7:24 am
by kev1n
Hi,

Clicking an anchor will change the url/reload the page. I added some JS code to override the default behaviour.

Note that I changed name="planning" to id="planning" etc.

This is my working example code:

Code: Select all

<ol>
<li><a href="#planning">Planning</a></li>
<ul>
    <li><a href="#planningteam"> Organise your team</a></li>
    <li><a href="#planningequipment"> Organise your equipment</a></li>
</ul>
</ol>


<h1><a id="planning"></a>Planning</h1>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<h2><a id="planningteam"></a>Organise your team</h2>
<br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br><br>
<h2><a id="planningequipment"></a>Equipment</h2>




<script>

var anchorlinks = document.querySelectorAll('a[href^="#"]')
 for (let item of anchorlinks) {
    item.addEventListener('click', (e)=> {
        let hashval = item.getAttribute('href')
        let target = document.querySelector(hashval)
        target.scrollIntoView({
            behavior: 'auto', // or smooth
            block: 'start'
        })
        history.pushState(null, null, hashval)
        e.preventDefault()
    })
}

</script>
Let me know if it works for you.

Re: Internal links in HTML object

Posted: Sun Jul 18, 2021 9:32 am
by nickrth
Works perfectly, thank so much for your help. Much appreciated.