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

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/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/#baz" -->
Desired behaviour:
<base href="http://example.com/" />
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->

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/">
/test
Anchor
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')
})
}
})

Building upon James Tomasino's answer, this one is slightly more efficient, solves a bug with double hashes in the URL and a syntax error.
$(document).ready(function() {
var pathname = window.location.href.split('#')[0];
$('a[href^="#"]').each(function() {
var $this = $(this),
link = $this.attr('href');
$this.attr('href', pathname + link);
});
});

A little bit of jQuery could probably help you with that. Although base href is working as desired, if you want your links beginning with an anchor (#) to be totally relative, you could hijack all links, check the href property for those starting with #, and rebuild them using the current URL.
$(document).ready(function () {
var pathname = window.location.href;
$('a').each(function () {
var link = $(this).attr('href');
if (link.substr(0,1) == "#") {
$(this).attr('href', pathname + link);
}
});
}

Here's an even shorter, jQuery based version I use in a production environment, and it works well for me.
$().ready(function() {
$("a[href^='\#']").each(function() {
this.href = location.href.split("#")[0] + '#' + this.href.substr(this.href.indexOf('#')+1);
});
});

You could also provide an absolute URL:
<base href="https://example.com/">
test
Rather than this
test

I'm afraid there is no way to solve this without any server-side or browser-side script. You can try the following plain JavaScript (without jQuery) implementation:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
element.href = location.href + element.getAttribute("href");
}
});
<base href="https://example.com/">
/test
#test
It also works (unlike the other answers) for dynamically generated (i.e. created with JavaScript) a elements.

If you use PHP, you can use following function to generate anchor links:
function generateAnchorLink($anchor) {
$currentURL = "//{$_SERVER['HTTP_HOST']}{$_SERVER['REQUEST_URI']}";
$escaped = htmlspecialchars($currentURL, ENT_QUOTES, 'UTF-8');
return $escaped . '#' . $anchor;
}
Use it in the code like that:
baz

To prevent multiple #s in a URL:
document.addEventListener("click", function(event) {
var element = event.target;
if (element.tagName.toLowerCase() == "a" &&
element.getAttribute("href").indexOf("#") === 0) {
my_href = location.href + element.getAttribute("href");
my_href = my_href.replace(/#+/g, '#');
element.href = my_href;
}
});

My approach is to search for all links to an anchor, and prefix them with the document URL.
This only requires JavaScript on the initial page load and preserves browser features like opening links in a new tab. It also and doesn't depend on jQuery, etc.
document.addEventListener('DOMContentLoaded', function() {
// Get the current URL, removing any fragment
var documentUrl = document.location.href.replace(/#.*$/, '')
// Iterate through all links
var linkEls = document.getElementsByTagName('A')
for (var linkIndex = 0; linkIndex < linkEls.length; linkIndex++) {
var linkEl = linkEls[linkIndex]
// Ignore links that don't begin with #
if (!linkEl.getAttribute('href').match(/^#/)) {
continue;
}
// Convert to an absolute URL
linkEl.setAttribute('href', documentUrl + linkEl.getAttribute('href'))
}
})

You can use some JavaScript code inside the tag that links.
<span onclick="javascript:var mytarget=((document.location.href.indexOf('#')==-1)? document.location.href + '#destination_anchor' : document.location.href);document.location.href=mytarget;return false;" style="display:inline-block;border:1px solid;border-radius:0.3rem"
>Text of link</span>
How does it work when the user clicks?
First it checks if the anchor (#) is already present in the URL. The condition is tested before the "?" sign. This is to avoid the anchor being added twice in the URL if the user clicks again the same link, since the redirection then wouldn't work.
If there is sharp sign (#) in the existing URL, the anchor is appended to it and the result is saved in the mytarget variable. Else, keep the page URL unchanged.
Lastly, go to the (modified or unchanged) URL stored by the mytarget variable.
Instead of <span>, you can also use <div> or even <a> tags.
I would suggest avoiding <a> in order to avoid any unwanted redirection if JavaScript is disabled or not working, and emulate the look of your <a> tag with some CSS styling.
If, despite this, you want to use the <a> tag, don't forget adding return false; at the end of the JavaScript code and set the href attribute like this <a onclick="here the JavaScript code;return false;" href="javascript:return false;">...</a>.

From the example given in the question. To achieve the desired behavior, I do not see the need of using a "base" tag at all.
The page is at http://example.com/foo/
The below code will give the desired behaviour:
bar <!-- Links to "http://example.com/bar/" -->
baz <!-- Links to "http://example.com/foo/#baz" -->
The trick is to use "/" at the beginning of string href="/bar/".

If you're using Angular 2 or later (and just targeting the web), you can do this:
File component.ts
document = document; // Make document available in template
File component.html
<a [href]="document.location.pathname + '#' + anchorName">Click Here</a>

Related

Change page title when div is :target

I'm working on a one single page navigation system; Is there is a way to change the <title> of a page when a div is :target (#divname in url)?
EDIT: Yeah, sorry, a Jquery/javascript solution works as well.
If the url contains #somePage, use #somePage as a selector and retrieve it's data-title value.
Then set <title></title> as that value. location.hash produces #somePage
$('a').click(function(event){
event.preventDefault();
if(location.hash) {
var newPageTitle = $(location.hash).data('title');
$('title').text(newPageTitle);
}
});
Add a data attribute to your div and set it's value to what the page title should be when that link is clicked.
Some Page
<div id="somePage" data-title="This Is The Page Title"></div>
It can be done in following way:
Assume that you have this html element:
<a onclick="onClick1()" href="#test">
link
</a>
and you have this scripts:
<script>
function onClick1(){
setTimeout(onClick,100);
}
function onClick(){
alert(1);
if(document.URL.indexOf("#test")>=0){
document.title = "Your title";
}
}
</script>
then you'll get on click what you need.
Here is example.

HTML onclick attribute with variable URL

Below code is for navigating to the Google Webpage when the element <li> is clicked.
<li onclick="window.location='http://www.google.com';" style="cursor:pointer;">Google</li>
Now I have another <li> which goes to different websites depending on a parameter. I tried this
<script>
document.write('<li onclick="window.location='http://www.google.com/mmm/yyy/' + random_variable + 'ddd/eee';" style="cursor:pointer;">Google</li>');
</script>
This isn't working fine. What am I doing wrong?
You don't want to use document.write. Instead you can change the attributes of the tags themselves. onClick is just javascript inside your code so you can replace variables
<li onclick="location.href='http://www.google.com/mmm/yyy/' + random_variable + 'ddd/eee';">Google</li>
It's a little messy. I'd personally do it with jQuery and a regular <a> tag
Javascript/jQuery
$(document).ready(function() {
$('#someid').click(function(e) {
e.preventDefault()
location.href= 'http://google.com/' + random_variable;
});
});
Or if your random variable is available onload you could just replace the href attribute
$(document).ready(function() {
$('#someid').attr('href','http://google.com/' + random_variable);
});
HTML
<li>Google</li>
var targetElement = document.getElementById("id");
targetElement.appendChild('<li>...</li>';
The first line find the existing element, where you want to insert the <li>.
The second line insert it.

Trying to put Bootstrap modal in a button

Is there a way I can use a button(input type="button") to show the Bootstrap modal. Basically the default is using anchor based on the documentation. I have tried experimenting but no luck.
I'm not sure if my coding is wrong or the Bootstrap modal can only be activated if it is an anchor tag. I have also tried googling or researching if anyone has created this kind of result.
This should work the same way as with an anchor tag.
The problem is, it's based on the href attribute, referring to the id of the modal window, and placing this attribute on a button might cause some html validation to go wonky.
If you don't care about that kind of stuff you can just replace your a tag with a button tag.
Edit: just noticed you were using an input element rather than a button. Either way, it should still work.
Edit2: Just verified if what I was saying wasn't total BS by looking at the bootstrap code (2.3.2), and found this snippet:
$(document).on('click.modal.data-api', '[data-toggle="modal"]', function (e) {
var $this = $(this)
, href = $this.attr('href')
, $target = $($this.attr('data-target') || (href && href.replace(/.*(?=#[^\s]+$)/, ''))) //strip for ie7
, option = $target.data('modal') ? 'toggle' : $.extend({ remote:!/#/.test(href) && href }, $target.data(), $this.data())
e.preventDefault()
$target
.modal(option)
.one('hide', function () {
$this.focus()
})
})
Looking at this, the href attribute isn't required, and you can use data-target instead when working with inputs and buttons.
simply u can fire event on Button Click and call function "onclick=showModal()"
JS CODE
function showModal()
{
$("#modal-window-id").modal("show");
}

Keep URL unaffected when anchor link is clicked

I've checked other posts on here, no results of what I'm looking for.
I want to click on
About
<div id="about">Content of this..</div>
and have it scroll to that element without putting www.domain.com/#about in the address bar
As a perfect example please check out this site that I found here and click on some of the links --they don't change the address bar when clicked.
You can do what you want using javascript and jquery, example below (note that this is using an old version of jquery):
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type='text/javascript'>
jQuery(document).ready(function($) {
$(".scroll").click(function(event){
event.preventDefault();
$('html,body').animate({scrollTop:$(this.hash).offset().top}, 1200);
});
});
</script>
</head>
<body>
<a class="scroll" href="#codeword">Blue Words</a>
<div id="codeword"></div>
</body>
</html>
Played around with this myself and here is a summary of my learnings on the subject.
Here's the basic link command:
Blue Words
Here's how you denote where the jump will scroll the page:
<A NAME="codeword">
Here's what's happening
The A HREF command is the same as a basic link except the link is to a codeword rather than a URL.
PLEASE NOTICE there is a # sign in front of the codeword. You need that to denote it is an internal link. Without the # sign, the browser looks for something outside the page named after your codeword.
Your "codeword" can be just about anything you want. I try my best to keep it short and make it denote what it is jumping to. There might be a limit to the number of letters you can use--but I haven't found it yet.
The point where the page will jump follows the same general format except you will replace the word HREF with the word NAME.
PLEASE NOTICE there is no # sign in the NAME command.
Note! Where you place the NAME target will appear at the top of the screen browser.
Hope it helps.
window.location.hash = ""
is the possible way I could find.
hash gives the string next to #.
//dont use a, use class
$(document).ready(function(){
$(".mouse").on('click', function(event) {
// Make sure this.hash has a value before overriding default behavior
if (this.hash !== "") {
// Prevent default anchor click behavior
event.preventDefault();
// Store hash
var hash = this.hash;
// Using jQuery's animate() method to add smooth page scroll
// The optional number (800) specifies the number of milliseconds it takes
to scroll to the specified area
$('html, body').animate({
scrollTop: $("#section").offset().top
}, 800, function(){
// Add hash (#) to URL when done scrolling (default click behavior)
window.location.hash = "";
});
} // End if }); });
One possible workaround is to use a <button> instead of a <a>.
So rather than....
About
<div id="about">Content of this..</div>
...you can change it to
<button href="#about">About</button>
<div id="about">Content of this..</div>
This way the anchor link will not affect the URL.
For me, only inserting "return false;" solved this issue.
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js" async></script>
<script>
jQuery(document).ready(function($) {
$('a[href^=#]:not(a[href=#])').click(function() {
$('html, body').animate({scrollTop: $(this.hash).offset().top}, 1300, 'easeInOutExpo');
return false;
});
});
</script>
(This applies to all anchor links on the page.)
I tried to monitor window.location.hash using a MutationObserver, but that doesn't work, see How to use (or is it possible) MutationObserver to monitor window.location.pathname change?
So now I'm using the window.onpopstate() eventListener:
var flag_onpopstate=false; // use this global flag to prevent recursion
window.onpopstate = () => {
if (flag_onpopstate) return;
flag_onpopstate = true;
window.location.hash = "";
flag_onpopstate = false;
}
A popstate event is dispatched to the window each time the active history entry changes between two history entries for the same document.

Is it possible to make a hidden section of a web page that is only visible when using an anchor link?

I would like to add a section to an existing webpage, but only make it visible if the user types the URL with a particular anchor link. Is this possible? Or is it possible to redirect to a new page if the URL has a certain anchor link?
Since you don't mind using JS, you can listen to the onhashchange event to decide whether the specific section should show.
http://jsfiddle.net/C3kHT/
window.addEventListener("hashchange",function(){
if(location.hash=="#trap") /*show section*/
},false);
Sorry that I don't have an IE 8 at hand, so I'm not sure if the fiddle code actually work in IE 8.
To redirect if a url has a certain anchor:
var anchor = "#tag";
var url = "http://www.google.com";
if(window.location.indexOf(anchor) !== -1){
window.location = url;
}
Maybe try this. Start out with your hidden section set to display: none;, then use jQuery to unhide it based on the hash in the url.
CSS:
.hiddenDiv {
display: none;
}
jQuery:
function showDiv() {
if (window.location.hash === '#hashNecessaryToShowDiv') {
$('.hiddenDiv').css('display', 'block');
}
}
showDiv();