Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make anchor links refer to the current page when using <base>

Tags:

html

href

When I use the HTML <base> tag to define a base URL for all relative links on a page, anchor links also refer directly to the base URL. Is there a way to set the base URL that would still allow anchor links to refer to the currently open page?

For example, if I have a page at http://example.com/foo/:


Current behaviour:

<base href="http://example.com/" /> <a href="bar/">bar</a> <!-- Links to "http://example.com/bar/" --> <a href="#baz">baz</a> <!-- Links to "http://example.com/#baz" --> 

Desired behaviour:

<base href="http://example.com/" /> <a href="bar/">bar</a> <!-- Links to "http://example.com/bar/" --> <a href="#baz">baz</a> <!-- Links to "http://example.com/foo/#baz" --> 
like image 935
Chris Down Avatar asked Nov 13 '11 01:11

Chris Down


People also ask

How do I link to an anchor on the same page?

To link to your newly-created named anchor, highlight the text, then click the Linkit button. In the "Link URL" field, add a "#" symbol and your anchor name: Click "Insert link" to add the link to your named anchor (on the same page).


1 Answers

I found a solution on this site: using-base-href-with-anchors that doesn't require jQuery, and here is a working snippet:

<base href="https://example.com/">  <a href="/test">/test</a> <a href="javascript:;" onclick="document.location.hash='test';">Anchor</a>

Or without inline JavaScript, something like this:

document.addEventListener('DOMContentLoaded', function(){   var es = document.getElementsByTagName('a')   for(var i=0; i<es.length; i++){     es[i].addEventListener('click', function(e) {       e.preventDefault()       document.location.hash = e.target.getAttribute('href')     })   } }) 
like image 86
davide bubz Avatar answered Sep 30 '22 08:09

davide bubz