Change div/span content by url addition? - javascript

I dont find a solution, so maybe its not possible with jquery?
My plan:
I have some divs like this:
<div>
<span class="en">Hello</span>
<span class="de">Hallo</span>
</div>
<div>
<span class="en">Whats up?</span>
<span class="de">Wie geht´s?</span>
</div>
aso.
So, if my url is just www.domain.com/..., only the "en"-content should be shown. If the url is www.domain.com/de/..., only the "de"-content should be shown. Is this possible with jquery?

You could do something like this:
var url = window.location.href; //Get URL
if (url.includes("/de/")) { //If URL Contains /de/
$('.en').hide();
} else {
$('.de').hide();
}
EDIT:
If you don't want to use includes due to browser support (as FlatLander points out in his answer, includes is ES6), then you can use indexOf:
var url = window.location.href; //Get URL
if (url.indexOf("/de/") !== -1) { //If URL Contains /de/
$('.en').hide();
} else {
$('.de').hide();
}

Cross browser support
includes is not available in all browser so try indexOf
var url = window.location.href;
if (url.indexOf("/de/") !== -1) { //If URL Contains /de/
$('.en').hide();
} else {
$('.de').hide();
}
includes is an es6 feature https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/includes#Browser_compatibility

Related

Js or Jquery: Get url and replace url to change language

I want make text link to change language
English: http://example.com/
Japan: http://jp.example.com/
When visitor on a page A (English)
example: http://example.com/A
I want make a text link, when visitor click , visitor go to Japan language with link like:
http://jp.example.com/A
I really thank for your help
call following method as onclick="switchLanguage()"
function switchLanguage() {
var url = window.location.href;
if (url.indexOf('jp.example.com') != -1)
window.location.href = url.replace('jp.example.com', 'example.com');
else
window.location.href = url.replace('example.com', 'jp.example.com');
}
Let's assume that your links will be inside
<div id="language-container">
</div>
In this case, let's ensure that we have a function like
function getLanguageLinks() {
let languages = {
"jp": "Japanese",
"": "English",
"ge": "German",
"hu": "Hungarian"
};
var links = [];
for (var key in languages) {
links.push('<p>${languages[key]}</p>');
}
document.getElementById("language-container") = links.join("");
}
and you are calling it in your body tag:
<body onload="getLanguageLinks()">
<!-- Some HTML -->
</body>

Change language code in URL using Javascript

I am developing a website that works in two languages. I need to change URL to include the selected language.
What I exactly need is:
Pick the current URL
Check if the URL contains any language code
Append the code if not exist or change the code to the selected one if exists
For example, there is an URL for English (default):
http://localhost:11767/Home/resultMain?model=1&&type=1
When a user selects Spanish (es) it should be:
http://localhost:11767/es/Home/resultMain?model=1&&type=1
You can parse the URL with the help of an a element then replace the part you want and re-build the URL :
function addReplaceLangCode(url, langCode) {
var a = document.createElement('a');
a.href = document.getElementById('url').value; // or document.location.href;
var paths = a.pathname.split('/');
paths.shift();
if(paths[0].length == 2) {
paths[0] = langCode;
}else{
paths.unshift(langCode);
}
return a.protocol + '//' +
a.host + '/' + paths.join('/') +
(a.search != '' ? a.search : '') +
(a.hash != '' ? a.hash : '');
}
function onClickReplace() {
document.getElementById('result').innerHTML = addReplaceLangCode( document.location.href, 'es');
}
URL : <input type="text" id="url" style="width:400px" value="http://localhost:11767/Home/resultMain?model=1&&type=1"><input type="button" value="Replace" onclick="onClickReplace()"><br />
Result: <span id="result"></span>
I don't know if it is exactly this, what you want. But JavaScript can obtain URL using object "location". Especially location.pathname is useful for you. You can apply reg-exp on location.pathname to check if URL contain /es/ and if yes, then translate website by proper Ajax requests to your backend.
But generally I recommending to use routing of your backend. The best solution in my opinion - use http headers to inform server about preferred language.
https://www.w3.org/International/questions/qa-accept-lang-locales
Based on #Bulnet Vural's answer above, I wrote the following code because I needed to toggle the language path in and out of the url.
var getOtherLanguageLocation = function (currentUrl, languagePath) {
// based on https://stackoverflow.com/a/42176588/1378980
var anchorTag = document.createElement('a');
anchorTag.href = currentUrl;
var paths = anchorTag.pathname.split("/");
// remove all the empty items so we don't get double slash when joining later.
var paths = paths.filter(function (e) { return e !== '' })
// the language will be at index 1 of the paths
if (paths.length > 0 && paths[0].toLowerCase() == languagePath) {
// remove the language prefix
paths.splice(0, 1);
} else {
// add the language prefix
paths.unshift(languagePath);
}
return anchorTag.protocol + '//' +
anchorTag.host + '/' + paths.join('/') +
anchorTag.search + anchorTag.hash;
};

Redirect url if checkboxes are selected

I have some problem with redirecting urls after checkboxes are selected. I am using document.location for this, but this doesn´t work in my code. I'm trying to fix it, but without success.
This is the part of my code which doesn't work:
function objednat() {
var adress = "";
if (document.getelementbyid('BoxtarifVolani1').checked == true) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/' + adresa;
}
I want to redirect this to a form, which will be filled with the selected values. I don't know why, but this document.location doesn't work in the code.
This is the part of the code I use in the formula for grabbing the hash from the url.
<script type="text/javascript">
if(window.location.hash) {
//set the value as a variable, and remove the #
var hash_value = window.location.hash.replace('#', '');
if (tarifVolani1 == true) {
document.getelementbyid('BoxtarifVolani1").checked = true;}
....
</script>
What am I doing wrong?
Whatever you have done is right, except, the function name is wrong case:
Change getelementbyid to getElementById.
Change adresa to adress.
Code:
function objednat() {
var adress = "";
if (document.getElementById('BoxtarifVolani1').checked == true) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/' + adress;
}
jQuery way of doing it
function objednat() {
var adress = "";
if ($('#BoxtarifVolani1').is(':checked')) {
adress += "#tarifVolani1";
}
window.location = 'http://www.investcon.webinpage.cz/cz/objednat-tarif-dobijeci-cislo/'+adress;
}
For your ref: jQuery :checked Selector

Links get appended to the current pages URL

I am trying to create an SOS page in which i am changing the links on the page after the button click. My problem here is that the links get changed but they get appended to the current pages URL.
My links do contain http:// (My reputation is less than 10 here)
Eg.
Originall link -- "htp://xyz.com?login_type=encrypted&login=&password="
Required link -- "htp://xyz.com?login_type=encrypted&loginxxx=&password=yyy"
Actual link that I am getting -- "htp://currentpageURL.com"htp://xyz.com?login_type=encrypted&login=&password=""
Here is the js I am using
function handleClick()
{
var uid, pwd;
uid = $("#uid").val();
pwd = $("#pwd").val();
if(uid != "" && pwd != "")
{
$("#links").show();
$("#login").hide();
$('a').each(function () {
var href = $(this).attr("href");
$(this).attr("href", href.replace("login=", "login=" + uid).replace("password=", "password=" + pwd));
});
}
else { alert("Please enter valid credentials"); }
}
You could find the "last part" of the script using the attached link and then just add the "login=" and "password="" to then end? See: this.href vs $(this).attr('href')

Get relative URL from absolute URL

I want to get the relative URL from an absolute URL in JavaScript using regex and the replace method.
I tried the following but it is not working:
var str="http://localhost/mypage.jsp";
document.write(str.replace("^[\w]*\/\/[\w]*$",""));
A nice way to do this is to use the browser's native link-parsing capabilities, using an a element:
function getUrlParts(url) {
var a = document.createElement('a');
a.href = url;
return {
href: a.href,
host: a.host,
hostname: a.hostname,
port: a.port,
pathname: a.pathname,
protocol: a.protocol,
hash: a.hash,
search: a.search
};
}
You can then access the pathname with getUrlParts(yourUrl).pathname.
The properties are the same as for the location object.
Below snippet returns the absolute URL of the page.
var myURL = window.location.protocol + "//" + window.location.host + window.location.pathname;
If you need only the relative url just use below snippet
var myURL=window.location.pathname;
Checkout get relative URL using Javascript for more details and multiple ways to achieve the same functionality.
If by "relative URL" you mean the part of the string after the first single /, then it's simple:
document.write(str.replace(/^(?:\/\/|[^/]+)*\//, ''));
This matches all the characters up to the first single / in the string and replaces them with the empty string.
In: http://localhost/my/page.jsp --> Out: /my/page.jsp
const url = new URL('https://www.example.com/path/#anchor?query=value');
const rel = url.toString().substring(url.origin.length)
console.log(rel)
// Output: /path/#anchor?query=value
Don't use low-level stuff like regexp etc. These things have been solved by so many other people. Especially the edge cases.
Have a look at URI.js, it should do the job: http://medialize.github.io/URI.js/docs.html#relativeto
var uri = new URI("/relative/path");
// make path relative
var relUri = uri.relativeTo("/relative/sub/foo/sub/file"); // returns a new URI instance
// relUri == "../../../path"
URL.getRelativeURL
There's an public-domain extension for the standard URL object called getRelativeURL.
It's got a few cool tweaks like force reload, you should check it out!
Try it live.       View on Gist.
Example usage
//syntax: <URL to convert>.getRelativeURL(<relative to this URL>)
//link from Mypage to Google
a = new URL("https://google.com/search");
a.getRelativeURL("https://mypage.com")
== "//google.com/search";
//link from the current location.href
a.getRelativeURL();
//link from Olutsee to Polk
var from = new URL("http://usa.com/florida/baker/olutsee");
var to = new URL("http://usa.com/florida/polk");
to.getRelativeURL(from) == "../../polk";
don't forget that \ is an escape character in strings, so if you would like to write regex in strings, ensure you type \ twice for every \ you need. Example: /\w/ → "\\w"
Below you can find script on that here we have only one problem which is one manual work, we want to add split attribute ie, if your site link is: Get relative URL from absolute URL
we want to url as below:
/questions/6263454/get-relative-url-from-absolute-url
so in below code we have to add .com instead of .net ie,
var res = at.split(".net"); here we want to add as per our requirement now i need to seperate after .com so code will be "var res = at.split(".com");".
i think you guys got that point if you have still doubt let me know please
and to see changes in code by inspecting:
$(document).ready(function(){
$("a").each(function(){
var at= $(this).attr("href");
var res = at.split(".net");
var res1 = res[0];
var res2 = res[1];
alert(res2);
$(this).attr("href",res2);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
<p>Hello World</p>
Change color
</div>
<div id="banner-message">
<p>Hello World</p>
Change color
</div>

Categories