1.21 gigawatts
1.21 gigawatts

Reputation: 17888

How to go to a link using the href value in JavaScript?

Due to design considerations I cannot put an Anchor tag around elements but I can add a click event to those elements.

How can I follow the link correctly?

Previous code:

<a href="Page1.html">
   <button>Page 1</button>
</a>

New code:

<button onclick="document.location.href= 'Page1.html'">Page 1</button>

With the code above testing locally I go from:

file://directory/to/home.html

to

file://Page1.html

But the page is in the same directory at:

file://directory/to/Page1.html

In other words I have to proceed without being able to use an anchor tag but do my best to represent it.

Should I add a title with the page location to show the target location? Is there a way to simulate the location that shows in the footer when hovering over a link?

Upvotes: 2

Views: 297

Answers (2)

Ritesh Khandekar
Ritesh Khandekar

Reputation: 4015

  • ./ Denotes your current directory's path
  • ../ Denotes your previous directory's path
  • / Denotes your root path

In above case you should add current Directory's path:

<button onclick="window.location.href='./Page1.html'">Page 1</button>

./Page%201 => will take you to file://directory/to/home.html

../Page%201 => file://directory/home.html

/Page%201 => file://Page%201

Upvotes: 1

CertainPerformance
CertainPerformance

Reputation: 371233

Use a relative path instead:

<button onclick="document.location.href='./Page1.html'">Page 1</button>

Even better, attach the listener properly using Javascript, since inline handlers are generally considered to be pretty poor practice, and have scoping and escaping issues:

document.querySelector('button').addEventListener('click', () => {
  window.location.href = './Page1.html';
});

You can use similar syntax to navigate up a level, without going all the way back to the root directory. Eg

window.location.href = '../Page1.html';

when running on

file://directory/to/home.html

will take you to

file://directory/home.html

Upvotes: 2

Related Questions