Clear the # without reloading the page - javascript

I am loading all website's pages into the main index page, and updating URL display by splitting the href into segments and adding the segments after the main domain name with .hash function, like this:
$('a').click(function(event) {
event.preventDefault();
var my_url = this.href;
var pathArray = this.href.split('/');
var newPathname = "";
for ( i = 3; i < pathArray.length; i++ ) {
newPathname += "/";
newPathname += pathArray[i];
}
$('body').load(my_url);
window.location.hash = newPathname;
This works okay, but I'm facing a little problem. When a user accesses http://www.mywebsite.com/ and then clicks, for example, on "About" link, the selected page loads, and the address bar displays:
http://www.mywebsite.com/#/about
But if a user starts with a different page:
http://www.mywebsite.com/#/about
Then after the click, the url becomes:
http://www.mywebsite.com/#/about/#/about
and so on, to infinity.
How can this be solved?
Perhaps there's a way to clear the hash and then display the new hash (that is, remove everything that starts with #/ and then add the new hash) – or maybe there's a better solution?

Try var my_url = this.href.replace(/#.*/,'')
This will remove the # and anything after it.

If you want to split just the path component of the current URL, then don’t use
var pathArray = this.href.split('/');
because href will contain the full path including the hash.
Use
var pathArray = this.pathname.split('/');
instead.

Changing the hash doesn't refresh your page. At most it forces the browser to scroll top. If you want you can do:
window.location.hash = "";
to empty it (retaining the #) if you also remove the #from the href then your page will always reload.

Related

Get current URL and add something in front with JavaScript

For a multi-language website, I want two buttons for the two languages that exist on the website.
The standard url would be: mydomain.com/something (this would be in german for example) The english url for this is: mydomain.com/en/something
How can I set up the buttons to get the current url/ page (in this case /something and add /en in front of it? Everything I found was to add stuff after the full domain.
Thank you very much.
check Location Obj MDM docs
console.log(document.location.origin + "/en" + document.location.pathname)
I'm not sure what your end goal is but if it involves reloading the same page with the localisation in the URL (i.e. on button click the page reloads and the page's URL is changed to mydomain.com/en/something meaning that on your next button click, the page would need to reload and its URL would need to be mydomain.com/something again) then you may need to look into RegEx and running it against the current URL to then swap out the URLs in the button so that on click you go to the correct version of the domain.
If the end goal is to only get the current URL and toggle whether the localisation appears in the URL or not then take a look at the snippet below which should hopefully help you out a bit.
For some further reading, I think these resources may be helpful for you:
RegEx: Regular expressions guide
RegEx: Regex101 - this is essentially a playground for practicing and testing your RegEx.
Location Object: MDN or W3Schools
jQuery(document).ready(function($) {
var $languageToggle = $('#language-toggle');
var origin = location.origin;
var pathname = location.pathname;
$languageToggle.on('click', function() {
var $this = $(this);
var toLanguage = $this.data('to-language');
var currentLanguage = $this.data('current-language');
var localisation = '';
/**
* This if statement will help prevent the constructedUrl variable
* from ever having a url such as https://website.com//page
* (notice the double forward slashes after .com).
*/
if (toLanguage) {
localisation = '/' + toLanguage;
}
var constructedUrl = origin + localisation + pathname;
$this.data('to-language', currentLanguage);
$this.data('current-language', toLanguage);
$('#output').text(constructedUrl);
});
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="output">Click on the toggle button</div>
<button id="language-toggle" data-to-language="en" data-current-language="">
Toggle language
</button>
var myFunc = () => {
window.location.href = window.location.href + "place you text here"
}
Click the button and the page will be edited
<button onclick="myFunc()">click me</button>

How to remove all URL hashes except first?

Well, on my site I have a FAQ where users can access specific questions through the URL, such that:
https://example.com/faq#question-1
And for this I use Jquery, such that:
if (window.location.hash) {
$(window.location.hash).open();
}
But I want that if the user enters more than one hash in the URL such that:
https://example.com/faq#question-1#question-2#question-3#question-n
All hashes are removed from the URL except the first #question-1
How can I do this?
Edit:
if user type https://example.com/faq#question-1#question-2#question-3#question-n then change the url to https://example.com/faq#question-1 so that only the first hash appears in the url and the FAQ only has to read a single hash.
It could something as simple as
var hash = window.location.hash;
var filtered_hash = '';
if(hash.length > 0){
filtered_hash = '#' + hash.split("#")[1];
window.location.hash = filtered_hash;
}
console.log(filtered_hash);
This should work for you
var str="https://example.com/faq#question-1#question-2#question-3#question-n";
var trimmedStr = str.split("#").slice(0,2).join("#");
console.log(trimmedStr);
This removes all hashes after the first hash.
You can use something like -
location.hash = '#'+location.hash.split('#')[1]

JavaScript how to include hash in variable that detects current domain?

My goal is to detect an href click and do something if the link is an external link. I have the following JavaScript in place to detect external links:
var isThisDomain = href.match(document.domain.split('.').reverse()[1] + '.' + document.domain.split('.').reverse()[0]);
I then use the following to do something if an external link is detected:
else if (href != isThisDomain) {
// do something for external links
}
This works for external links but also fires for internal links with a #. For example, if my site is www.example.com I DO NOT want this to fire if href is www.example.com/#anchor or www.example.com/category/#anotheranchor.
How do I change isThisDomain to cater for this hash?
Have you tried using document.location.hostname (which only gets the host name part of the URL and excludes everything else) and comparing it to the URL you have?
If you're doing this to every link on the page, you'll need to set an EventListener on all links that check the host property on them. If it's external, do whatever you need to. It looks like this:
function checkHref(e) {
var url = e.target.href,
externalUrl = e.target.host !== document.location.hostname;
if (externalUrl) {
console.log(e); // Place your logic here.
}
e.preventDefault();
}
var links = document.getElementsByTagName('a'),
i;
// Loop through all anchor elements and add an EventListener
for (i = 0; i < links.length; i++) {
var el = links[i];
el.addEventListener('click', checkHref, false);
}

Removing # and its value from url

I have seen posts on here to remove the hash value from a url... but how do remove the value and the # itself.
for example if a url was
mysite.com
and when a user navigates through the one page application the url might change to
mysite.com#mytest
so when they reload it i just want it to show
mysite.com and not mysite.com#mytest
these two just remove the value
location.hash = 'home';
window.location.replace("#");
thanks
var href = window.location.href;
var index = href.indexOf('#');
if ( index > 0) {
window.location = href.substring(0, index);
}
I don't think it's possible to remove the hash without reloading the page.

Get current URL and modify subdirectory and then go to URL with Javascript

I'm creating a bilingual website for a client. Two versions of the site in different languages will be created and stored in two folders:
/en/
/chi/
What I want to do is create a link to toggle between the two languages. On the conceptual level, I understand that Javascript can detect the current URL and split it into its different components, modify parts of it (in this case change between /en/ and /chi/), and then go to that new URL when the link is clicked.
But I have zero knowledge in javascript so I have no idea how to execute... I have come across this page:
http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
but it doesn't explain how to modify and go to the new link.
You help will be greatly appreciated!!
To not break usability considerations like Shift + Click to open in a new window, you should create a plain old link (<a>) that points to the other language URL. There's nothing wrong with building the link via JavaScript, but you could also do it on the server using PHP or whatever templating language you're using.
Here's a script that does this with JavaScript if that's what you decide you'd like to do.
<!DOCTYPE html>
<body>
Content before the link.
<script>
(function () {
// this assumes you're on the en version and want to switch to chi
var holder = document.createElement("div");
var url = window.location.href.replace("/en/", "/chi/");
var link = document.createElement("a");
link.innerText = "Chewa"; // or whatever the link should be
link.href = url;
holder.appendChild(link);
document.write(holder.innerHTML);
})();
</script>
Content after the link.
</body>
If you simply want to take the full URL and replace /en/ with /chi/ or vise-versa, use the code below.
HTML
<span onclick="SwitchLang()">View [Some other Language]</span>
JavaScript
function SwitchLang() {
//Does URL contain "/en/"?
if(window.location.href.indexOf("/en/") != -1) {
//URL contain "/en/", replace with "/chi/"
window.location.href = window.location.href.replace("/en/", "/chi/");
}
//Does URL contain "/chi/"?
else if(window.location.href.indexOf("/chi/") != -1) {
//URL contain "/chi/", replace with "/en/"
window.location.href = window.location.href.replace("/chi/", "/en/");
}
}
Or, a bit more concise (un-commented version)
function SwitchLang() {
if(window.location.href.indexOf("/en/") != -1)
window.location.href = window.location.href.replace("/en/", "/chi/");
else if(window.location.href.indexOf("/chi/") != -1)
window.location.href = window.location.href.replace("/chi/", "/en/");
}
Note: In JS, when you modify window.location.href, the new URL is automatically loaded.
Here's a working fiddle for you to play with.
It looks like you need to change the window.location.pathname. For example:
// assuming the url `http://www.example.org/en/foo/bar/page.html`
var paths = window.location.pathname.split("/");
// change `en`
paths[1] = "chi";
// go to the new url
window.location.pathname = paths.join("/");
See:
https://developer.mozilla.org/en/DOM/window.location

Categories

Resources