Add language suffix to url if it doesn't exist already (javascript) - javascript

I have a multi language site and people come in via links WITH a url suffix (/lang/en for instance) or WITHOUT a suffix (just the page url).
Now I want to create the language switch function with a link (with a class to trigger the javascript).
My link class will be "english" for instance and in the JS I first need to check if there isn't a language suffix to the url already before I append it.
Here's what I have right now (from another thread):
<a class="english" href="">English</a>
<script>
$('.datalink').attr('href', function() {
return this.href + '/lang/en';
});
</script>
This adds the suffix but Without checking if it already exists, how do I check if it is already there and not append it? or change it to another language (/lang/nl)?
UPDATE
Actually my class is not on the href but on the <li> around it, it looks like:
<li class="english"><a title="English">English</a></li>
so now I have
$('.english >a').attr('href', function() {
var suffix = this.href.match(/lang\/en\/?$/i) ? "" : "/lang/en";
return this.href + suffix;
});
NOTE Wat I want to achieve is two links on each page of my website that will consist of the basic page url with a
lang/en
or
lang/nl
suffix to them. When clicked those links will load the same page but with the language suffix in the url, my language plugin will pick that up an present the language.

You can use a regular expression to check if the URL contains the suffix:
if (this.href.match(/lang\/en\/?$/i)) {
/* CONTAINS THE SUFFIX */
} else {
/* DOESN'T CONTAIN IT */
}
The way that I'd probably do it is as follows:
$('.datalink').attr('href', function() {
// suffix is blank if the URL already contains the language portion
var suffix = this.href.match(/lang\/en\/?$/i) ? "" : "/lang/en";
return this.href + suffix;
});

Somehow the none of the above javascript worked for me, I don't know what I was doing wrong but finayl I decided to resort to php cause I understand that much better. I use this on a wordpress site and I came up with the following code (in theme functions.php) that worked for me:
// add languages to menu
add_filter('wp_nav_menu_items','add_langs', 10, 2);
function add_langs($items, $args)
{
if( $args->theme_location == 'primary-menu')
$current_url = ( is_ssl() ? 'https://' : 'http://' ) . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
$href = str_replace(array('/lang/en','/lang/nl'),'',$current_url);
$english = '<li class="english">EN</li>';
$nederlands = '<li class="nederlands">NL</li>';
return $items . $english . $nederlands ;
}
This finds my menu called "primary-menu" and adds two items to this menu consisting of $english and $nederlands links.
I had to get the page url with $_server['HTTP_HOST'] instead of get_permalink() cause that one returned a random url somehow. the first one always works and with the str_replace I replace the language additions first if they exist (str_replace doesn't need an if statement, it always checks if it exists before replacing)
Hope this helps someone else out, still wondering why the javascript didn't work for me!

if it is a suffix that always starts with /lang, try this
Live Demo
$('.english a').each(function() {
$(this).attr('href', this.href.split("/lang")[0] + '/lang/en');
});
or if you want to keep one if there
$('.english a').each(function() {
var href = this.href;
var pos = href.indexOf("/lang/");
if (pos == -1) $(this).attr('href', href.substring(0,pos)+'/lang/en');
});

Related

taking the # out of url on location.hash

function updateView(category) {
console.log( window.location.hash );
if (location.hash !== ""){
//convert #3 to 3.
//load video based on id
//myArray[sanitizedHash];
} else {
updateCategoryLabel(category);
currentList = updateVideosList(category);
chooseRandomVideoFromList();
}
}
This function is loaded on page load
How can I parse inside this function so that the the location.hash's '#' will be taken out of the URL?
In short I am trying to achieve www.mysite.com/3 versus www.mysite.com/#3
Thanks in advance!
Edit: I should add that the 'else' is basically randomizing on page load versus going to the direct url. This if statement will run on page load to check if the hash exists otherwise it will randomize as usual.
Altering the URL from 'www.mysite.com/#3' to 'www.mysite.com/3' will cause the browser to navigate to a new URL since www.mysite.com/3 is not the same page as www.mysite.com/#whatever.
If you just want a string with the first character of the hash trimmed try:
window.location.hash.substr(1)
You can get the window.location.hash and then replace the # with an empty string
if (location.hash !== ""){
var sanitizedHash = window.location.hash.replace("#", "");
//load video based on id
//myArray[sanitizedHash];
}
If your goal is NOT to trigger page load, you can use HTML5 History API to change URL from www.mysite.com/#3 to www.mysite.com/3 like that:
var id = location.hash.substr(1);
history.replaceState({id:id}, id, id);
Note that replaceState is used, because otherwise user can press back button to the browser and get back to the #3. If you want to allow that, replace replaceState with pushState. Hope that helps.

Changing how URL parameters are appended to links based on destination

My company is serving up PPC landing pages with Unbounce (on a subdomain), which then links back to our website. We're using the following code to append the AdWords gclid variable to outgoing links:
$(document).ready(function() {var params = window.location.search.replace(/\+/g,'%20'); var button = $('a').each( function(i) {this.href = this.href + params;});});
The issue arises when the Gclid gets appended to a URL that already has a parameter (like our checkout forms). You end up with a URL that looks like this:
domain.com/checkout?EventID=15546?Gclid=jdkI324kd
I'm wondering if there's a way to change the Glid's '?' to an '&' for certain URLs that already have parameters, while keeping the existing functionality of using the '?' for the others.
Thanks!
Edit: Seems like there's some redirection going on, this is how the href looks for the links in question:
http://domain.com/lp/clkg/https/domain.com/cart.aspx?EventID=125160?gclid=CPfO1JaOx7oCFQZyQgod5A4AFw
Simply replace it yourself:
$(document).ready(function() {
var params = window.location.search.replace(/\+/g,'%20');
var button = $('a').each( function(i) {
if (this.href.indexOf('?') == -1) {
this.href = this.href + params;
} else if (params.length) {
this.href = this.href + '&' + params.substr(1);
}
});
});
Edit: and are you aware that you are replacing subsequent spaces with only one single '%20'?

Regular expression to check current website location - small issue

I have this jquery code to highlight menu item corresponding to current page in my browser:
$(document).ready(function (){
$("ul#nav a").each(function (){
var hrefWindow = $(this).attr("href");
if (hrefWindow == window.location.href.match(/[^/]+$/g)) {
$(this).parent().addClass("active");
}
else {
$(this).parent().removeClass("active");
};
});
})
As you can see expression is looking for string which is just after slash in my web address like:
www.mywebsite.com/thisStringWillBeFoundByExpression ,
everything works fine but there is small issue when I type my domain address for the first time as there will be only www.mywebsite.com (without index.htm after slash) in address bar and my expression won't find a thing.
How to modify my code to add class 'active' to index.htm in case if there is only www.mywebsite.com in the address bar?
I'd suggest to use location.pathname instead of parsing href:
var path = location.pathname.substring(1);
$(this).parent().toggleClass("active", !hrefWindow || path === hrefWindow);
REF: https://developer.mozilla.org/en-US/docs/DOM/window.location#Properties

Replace links on page based on location.host and a cookie

I'm using jquery to rewrite a list of links on the page. If the location.host is NOT the vendor location.host AND the cookie isn't set to a specific value then it locates the links and rewrites them to the alternate values. The code I'm using works great in FF but not in IE7. Please help!
<script type="text/javascript">
// link hider
var hostadd = location.host;
var vendor = '172.29.132.34';
var localaccess = 'internal.na.internal.com';
var unlock = 'http://internal.na.internal.com/Learning/Customer_Care/navigation/newhire.html';
// link rewriter
$(document).ready (
function style_switcher(){
//if not a vendor or not accessing from lms reroute user to lms
if (hostadd != vendor && $.cookie("unlockCookie") != unlock){
var linkData = {
"https://www.somesite.com": "https://internalsite.com/something",'../Compliance/something/index.html':'../somethingelse.html'
};
$("a").each(function() {
var link = this.getAttribute("href"); // use getAttribute to get what was actualy in the page, perhaps not fully qualified
if (linkData[link]) {
this.href = linkData[link];
}
});
}
});
</script>
What you could do, if you insert the links dynamic, is store them in a data attribute like data-orglink="yourlink" which wouldnt be transformed by the browser, then check on that -and if its in the object array - change the href. Do you have access to creating the data attribute?
IE7 have problems with internal links, because it puts the host info on, before JS can reach the link..
http://jsfiddle.net/Cvj8C/9/
Will work in all, but IE7. So you need to use full paths if to use JS for this function :(
You had some errors in your JS.
But it seems to work fine?
See: http://jsfiddle.net/s4XmP/
or am i missing something? :)

JavaScript: Show / Hide <DIV> based on URL string

I need to show a DIV on two pages (URL's) but not on the others.
(I have jQuery on the pages if that helps.). I'm a complete noob so all help is very much appreciate. Thank's!
Case (1) where I want to show the DIV:
On the start page, when the web browser address field reads 'www.mydomin.com'
The start page is PHP so I guess the full URL is 'www.mydomin.com/index.php'
Case (2):
'www.mydomin.com/index.php?option=com_myblog&title.html&Itemid=1&lang=en'
WHERE this part is alway the same
'www.mydomin.com/index.php?option=com_myblog&'
AND this part is always unique
'title.html&Itemid=1&lang=en
Example
if (url == 'www.mydomin.com' or 'www.mydomin.com/index.php?option=com_myblog&') {
do this
xxxxxxxx
else
nothing
This should work, if I understand the question correctly
var url = document.location.href;
if (url.indexOf('www.mydomin.com/index.php?option=com_myblog&') >= 0) {
$('#div_id').hide();
} else {
$('#div_id').show();
}
But really, if you use PHP anyway, you should figure out how to not render the div in the first place.
You can parse the query string and show/hide the div based on the result.
I also think it should be handled from PHP code instead from JavaScript. And div should not be rendered in first place.
You can target a specific query parameter of the URL using window.location.search. Using the below code, you can find an exact match anddisplay/hide the HTML element:
var firstURLParam = window.location.search.substring(1).split('&')[0];
var datGuiEle = document.getElementById("elemID");
if(firstURLParam == "debug"){
datGuiEle.style.display = "block";
}
else {
datGuiEle.style.display = "none";
}

Categories