0

I have something like this:

<a name="position">Position</a>

<a href="#position">Go to target position</a>

By using jquery, is it possible by some way, when clicking the anchor it follows the link but NOT place the "#position" on the URL address?

I tried e.preventDefault() on clicking the anchor, but that stops following the link!

evilReiko
  • 19,501
  • 24
  • 86
  • 102

2 Answers2

1

I think this has been addressed before:

How to remove the hash from window.location with JavaScript without page refresh? The only difference would be that you would have to do window.location.href = (whatever the above resulted in).

Community
  • 1
  • 1
Richard Andrew Lee
  • 1,187
  • 6
  • 10
  • What I want is this: (1) Clicking anchor takes user to target link (2) Since the target link on same page, no page refreshing is needed (3) I don't want to print #text on the URL address – evilReiko Oct 13 '11 at 08:01
  • Ya I totally get it. /: see here: http://stackoverflow.com/questions/824349/modify-the-url-without-reloading-the-page – Richard Andrew Lee Oct 14 '11 at 00:21
1

see if this works: http://jsfiddle.net/uzpcV/25/

extracting the "#id" scrolling to that location then canceling our the original click functionality

$(document).ready(function() {

function addClick(anchor,theUrl,i){
     anchor.click(function() {
            var whereToGo = theUrl.substr(theLocation);

            $('html, body').animate({
                scrollTop: $(eval('"' + whereToGo + '"')).offset().top
            }, 333);

            //hold it right there  
            return false;

        });
}

var allTheLinks = $("a");
var linksLength = allTheLinks.length;

//go through all the links   
for (var i = 0; i < linksLength; i++) {

    var theLink = allTheLinks.eq(i);
    var theUrl = theLink.attr("href");
    var theLocation = theUrl.indexOf("#");


    //check for #
    if (theLocation > -1) {
       addClick(theLink,theUrl,i)
    }
}
});
Richard Andrew Lee
  • 1,187
  • 6
  • 10