Alfred
Alfred

Reputation: 21406

How to go to url in same server without setting complete url address - JavaScript (with/without) jQuery

I know how to go to link / url / address, like;

window.location = "www.example.com/index.html";

or

document.location.href="www.example.com/index.html";

But suppose I want to navigate from index1.html to index2.html, how can i achieve this without providing the www.example.com/ prefix? Please don't suggest that I set www.example.com/ in a global variable / constant. The address may change to www.example2.com/subfolder1/subfolder2/ to www.examplea.com/.... The mentioned methods works only in the case of root pages. I mean, providing document.location.href="index.html"; will navigate the browser to rootdomain/index.html, even if I am staying in rootdomain/section1/section2/somepage.html. But I want to navigate to rootdomain/section1/section2/index.html

How can I achieve this by providing just the page name?

Upvotes: 0

Views: 1019

Answers (3)

Noyo
Noyo

Reputation: 5144

window.location.pathname = 'index2.html';

You can also just use relative urls on the document.location.href.

What might be even better is window.location.assign('index2.html');. This is especially useful when you're at www.example.com/foo/.../index1.html and don't want to specify the whole path to get to www.example.com/foo/.../index2.html.

For more options, see https://developer.mozilla.org/en-US/docs/DOM/window.location .

Upvotes: 0

Xymostech
Xymostech

Reputation: 9850

If you have a / at the beginning of your string, it'll go to the local page:

window.location = "/index.html"

Upvotes: 1

Fleming Slone
Fleming Slone

Reputation: 177

Just like you would do otherwise, but using the relative path:

document.location.href = '/index2.html'; //relative path

Upvotes: 0

Related Questions