Home > Software design >  How to navigate to a section in the page without using id?
How to navigate to a section in the page without using id?

Time:08-08

I know you can navigate to a section in the page using anchor tags, but doing this adds unwanted keywords to the URL.

So if the original URL was www.xyz.com, clicking on an anchor tag <a href="#abc">abc</a> would change the URL to www.xyz.com/#abc. I do not want the URL to change since this every time you click on "back", it just goes to the previous section that the URL held previously. Is there any way to stop this from happening? Maybe reroute the back button to leave the website or something?

CodePudding user response:

Have you tried using JavaScript? Use scrollintoview function. Here's an example:

<a onclick="scrollthere()">go to the content<\a>

<h1 id="stophere">This is content</h1>

<script>
function scrollthere(){
var element = document.querySelector("#stophere");

element.scrollIntoView();
}
</script>

Something like that. Onclick is an event. And in brackets we write function that we want to execute when clicked on it. In our case it's scrollthere which scrolls to our h1 element that has is "stophere". It will scroll untill our element won't get into view. You could read more about it here . Good luck with your website. I'm making website as well :).

CodePudding user response:

My solution is to use JS instead of using <a> behavior.

for example

document.querySelectorAll("a").forEach((item, idx) => {
    item.addEventListener("click", (e) => {
        e.preventDefault();

        const hash = e.target.hash;

        window.scrollTo({
            top: document.querySelector(hash).offsetTop,
            behavior: "smooth"
        });
    });
});
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.section {
    width: 100%;
    height: 100vh;
}

.sec-1 {
    background-color: salmon;
}

.sec-2 {
    background-color: teal;
}
<a href="#sec-1">Section 1</a>
<a href="#sec-2">Section 2</a>

<div id="sec-1" ></div>
<div id="sec-2" ></div>

In my case, I use the scrollTo() property.

Hope this might help you.

CodePudding user response:

You can set your href attribute to empty string.

<a href="">abc</a>
  • Related