8

I am currently using jQuery to load a page at a specific hashtag (via onload function in the body class) when a user clicks on a post title. The hashtag obviously shows up in the url. I was wondering if there was a way to hide the hashtag from cluttering up the URL. Did some searches and did not come up with much.

function goToAnchor() {
    location.href = "#post";
}
chris_s
  • 1,051
  • 4
  • 14
  • 28

4 Answers4

22

As seen here: http://djpate.com/2009/10/07/animated-scroll-to-anchorid-function-with-jquery/

function goToByScroll(id){
    $('html,body').animate({scrollTop: $("#"+id).offset().top},'slow');
}

Just pass the id of the element you wish to scroll to.

Jeff Hines
  • 3,511
  • 1
  • 19
  • 21
  • I guess I forgot to mention that this is in wordpress. So when I click a link on the blog post page, I would like it to scroll to the title. I tried using this, and following the instructions in the link and I couldn't get it to work... any suggestions? – chris_s Apr 21 '12 at 01:28
  • 1
    Can you ensure that the function is getting called when you click on a link? Try putting `alert()` in there. – Jeff Hines Apr 23 '12 at 18:31
6

You can bind a click event to this particular kind of anchor, and prevent default on it:

$('.anchorClass').on('click', function(e) {
  e.preventDefault();
  // rest of stuff
});

The "rest of stuff" means locating some sort of plugin or code sample that will jump the page. If you want it to roll along smoothly, there's a scrollTo plugin that's quite popular. It might even be that the scrollTo plugin takes care of the default prevention.

[update]

Jeff's suggestion (assuming it works) is the "rest of stuff" and is the more useful of the two answers. ;-) But preventing default is still important.

Greg Pettit
  • 10,749
  • 5
  • 53
  • 72
1

Jump/Smooth scroll to anchor tag without showing hashtag in URL

TRY DEMO

function scrollSmoothTo(elementId) {
  var element = document.getElementById(elementId);
  element.scrollIntoView({
    block: 'start',
    behavior: 'smooth'
  });
}
#userdiv {
  margin-top: 200px;
  width: 200px;
  height: 400px;
  border: 1px solid red;
}

a {
  color: #337ab7;
  cursor: pointer;
}

a:hover {
  text-decoration: underline;
}
<a onclick="scrollSmoothTo('userdiv')">
  Scroll to userdiv
</a>

<div id="userdiv">
  Lorem ipsum this is a random text
</div>
Manoj Selvin
  • 2,247
  • 24
  • 20
0

I think you can just use the .htaccess file. There you can make some url links go at the same address.

For example fff.com/fff and fff.com and fff.com#anchor can be shown as fff.com on the browser's tab.

Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339