[javascript] anchor jumping by using javascript

I have a question that will be found very often. The problem is that nowhere can be found an explicit solution.

I have two problems regarding anchors.

The main goal should be to get a nice clean url without any hashes in it while using anchors to jump on a page.

So the structure of the anchors is:

<ul>
    <li><a href="#one">One</a></li>
    <li><a href="#two">Two</a></li>
    <li><a href="#three">Three</a></li>
</ul>

<div class="wrap">
    <a name="one">text 1</a>
    <a name="two">text 2</a>
    <a name="three" class="box">text 3</a>
</div>

Okay, if you will click one of the links the url will automatically change to

www.domain.com/page#1

At the end this should be just:

www.domain.com/page

So far, so good. Now the second thing is, when you search the internet for that problem you will find javascript as a solution.

I have found this function:

function jumpto(anchor){
    window.location.href = "#"+anchor;
}

and calling that function with:

<a onclick="jumpto('one');">One</a>

what will be the same like before. It will add the hash to the url. I also added

<a onclick="jumpto('one'); return false;">

without success. So if there is someone who could tell me how to solve this I really would appreciate.

Thanks a lot.

This question is related to javascript html function anchor href

The answer is


Not enough rep for a comment.

The getElementById() based method in the selected answer won't work if the anchor has name but not id set (which is not recommended, but does happen in the wild).

Something to bare in mind if you don't have control of the document markup (e.g. webextension).

The location based method in the selected answer can also be simplified with location.replace:

function jump(hash) { location.replace("#" + hash) }

Because when you do

window.location.href = "#"+anchor;

You load a new page, you can do:

<a href="#" onclick="jumpTo('one');">One</a>
<a href="#" id="one"></a>

<script>

    function getPosition(element){
        var e = document.getElementById(element);
        var left = 0;
        var top = 0;

        do{
            left += e.offsetLeft;
            top += e.offsetTop;
        }while(e = e.offsetParent);

        return [left, top];
    }

    function jumpTo(id){    
        window.scrollTo(getPosition(id));
    }

</script>

I have a button for a prompt that on click it opens the display dialogue and then I can write what I want to search and it goes to that location on the page. It uses javascript to answer the header.

On the .html file I have:

<button onclick="myFunction()">Load Prompt</button>
<span id="test100"><h4>Hello</h4></span>

On the .js file I have

function myFunction() {
    var input = prompt("list or new or quit");

    while(input !== "quit") {
        if(input ==="test100") {
            window.location.hash = 'test100';
            return;
// else if(input.indexOf("test100") >= 0) {
//   window.location.hash = 'test100';
//   return;
// }
        }
    }
}

When I write test100 into the prompt, then it will go to where I have placed span id="test100" in the html file.

I use Google Chrome.

Note: This idea comes from linking on the same page using

<a href="#test100">Test link</a>

which on click will send to the anchor. For it to work multiple times, from experience need to reload the page.

Credit to the people at stackoverflow (and possibly stackexchange, too) can't remember how I gathered all the bits and pieces. ?


I think it is much more simple solution:

window.location = (""+window.location).replace(/#[A-Za-z0-9_]*$/,'')+"#myAnchor"

This method does not reload the website, and sets the focus on the anchors which are needed for screen reader.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to function

$http.get(...).success is not a function Function to calculate R2 (R-squared) in R How to Call a Function inside a Render in React/Jsx How does Python return multiple values from a function? Default optional parameter in Swift function How to have multiple conditions for one if statement in python Uncaught TypeError: .indexOf is not a function Proper use of const for defining functions in JavaScript Run php function on button click includes() not working in all browsers

Examples related to anchor

How to open a link in new tab using angular? Attaching click to anchor tag in angular How to create a link to another PHP page Making href (anchor tag) request POST instead of GET? Difference between _self, _top, and _parent in the anchor tag target attribute How can I create a link to a local file on a locally-run web page? How to open link in new tab on html? Getting a link to go to a specific section on another page Pure CSS scroll animation Make anchor link go some pixels above where it's linked to

Examples related to href

File URL "Not allowed to load local resource" in the Internet Browser Angular 2 router no base href set How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template? Html- how to disable <a href>? Add php variable inside echo statement as href link address? ASP MVC href to a controller/view href="tel:" and mobile numbers How can I disable the bootstrap hover color for links? How can I disable HREF if onclick is executed? Open link in new tab or window