Skip to content Skip to sidebar Skip to footer

Javascript To Make The Page Jump To A Specific Location

I there a way in javascript to make the page jump to a specific location on the page, such as I do not want to re=load page,

Solution 1:

You can set the location.hash property, like this:

window.location.hash = "jump_to_this_location";

You can give it a try here.

Solution 2:

2020 Answer

A simple and modern way to do this would be like this:

document.getElementById("jump_to_this_location").scrollIntoView({behavior: 'smooth'});

The behaviour: 'smooth' argument makes the jump... well... smooth. Which is something probably most of you want.

Solution 3:

If you use jQuery it's pretty simple here is some sample code

Bellow is the #nav where I stored all the clickable links to the articles in this example

Note: I used the goto attribute(custom) to pass the ID for the target Article

<divid='nav'><divgoto='text1'>Link To Text 1</div><divgoto='text2'>Link To Text 2</div></div>

Here, bellow are the Articles you will be jumping to.

Note: The JavaScript in the last code sample takes the distance of the tag to the top of that page and then scrolls the page down by that same distance measurement taken.

<divid='articles_container'><article><h1id='text1'></h1><p>
    Sample article Paragraph 1
  </p></article><article><h1id='text2'></h1><p>
    Sample article Paragraph 2
  </p></article></div>

Finally this is the javascript + jQuery that makes it all work, this solution is best when you are working with fixed and layered components.

<script>
        $(document).ready(function(){
          $('#nav div').click(function(){
            var id = "#" + $(this).attr('goto');
            var top = $(id).position().top;
            $('html').scrollTop(top);
          });
        });
</script>

Solution 4:

This can be accomplished by first creating an anchor for the page landing spot using HTML.

<aname="jumpHere">somewhere</a>

Once you have the landing site, simply use the JavaScript:

window.location = 'yoursite.html#jumpHere';

Solution 5:

I realize this question is five years old, but people still find it, and it seems a shame no one has ever answered it...

Specifically "Without Reloading Page" as asked,

and where there is a name="HERE" or id="HERE" label somewhere in the html ("HERE" is of course an example of any label),

then Javascript can do:

if (navigator.userAgent.match(/Chrome|AppleWebKit/)) { 
    window.location.href = "#HERE";
    window.location.href = "#HERE";  /* these take twice */
} else {
    window.location.hash = "HERE";
}

Works for me.

Post a Comment for "Javascript To Make The Page Jump To A Specific Location"