Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Onclick change url using jquery

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/

like image 930
Prithviraj Mitra Avatar asked Dec 09 '13 16:12

Prithviraj Mitra


2 Answers

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.

like image 103
aksu Avatar answered Sep 21 '22 11:09

aksu


instead of window.location you need to modify the history

example code

var stateObj = { foo: "bar" };
history.pushState(stateObj, "page 2", "bar.html");
like image 36
marvwhere Avatar answered Sep 22 '22 11:09

marvwhere