13

I am trying to change a url using jquery.

So once the button is clicked it will change the parent url but it will not redirect.

For example, If the url is,

http://www.xyz.com then it will become http://www.xyz.com/abc but will not be redirected.

My Code:

$('.clickme').click(function () {
    window.location.hash = 'xyz';
});

Is it at all possible?

Please suggest.

JSfiddle : http://jsfiddle.net/squidraj/Tn8BW/3/

8
  • 4
    Yes it is possible. Show us your code so far and we will see where you went wrong. Also do you mean the URL on the anchor tag or the URL in the address bar? Commented Dec 9, 2013 at 16:26
  • stackoverflow.com/questions/352343/… Commented Dec 9, 2013 at 16:26
  • 1
    are you using window.location? Commented Dec 9, 2013 at 16:27
  • @Huan The fiddle is added. Commented Dec 9, 2013 at 16:33
  • 1
    jsfiddle.net/aamir/Tn8BW/4/show Commented Dec 9, 2013 at 16:36

2 Answers 2

27

Javascript can luckilly modify browser's history, and change the url. This example will add new row to your browser's history, and you are able to use back button to go to that page.

HTML:

<a href="http://www.xyz.com/abc" id="link">abc</a>

jQuery:

$('#link').click(function() {
   window.history.pushState('obj', 'newtitle', '/abc');
   return false;
});

Or if you want to use url hashes(like in your code):

$('#link').click(function () {
    window.location.hash = 'xyz';
    return false;
});

That will not redirect, it stays on the page.

Sign up to request clarification or add additional context in comments.

9 Comments

Thanks @aksu. In first example is it supported by all browsers/versions?
It's supported pretty generally, even in some of the mobile browsers! you can check more on caniuse.com/#feat=history.
Search engines ingnore hashtags, so they will not indexed. You can read more on that blog phoenixrealm.com/the-power-of-the-hash-in-seo
I would downvote, but my reputation is to low... never ever use "return false" for this.What you want to do is "event.preventDefault()"!
It's easier to remember.
|
3

instead of window.location you need to modify the history

example code

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.