Regular expression to check current website location - small issue - javascript

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

Related

javascript check if a string exists on page

I am working on checking if string exists on page. And I have some difficulties. I have url that generated by system var url = here it generated it in string format and its in "string" format. So lets say it has for of "url/my" and "url/yours" I make it to be url by #text I need to check if it contains exact word on page in generated url
<script type='text/javascript'>
window.onload = function () {
if (document.body.innerHTML.toString().indexOf('something') > -1) {
alert("It contains 'something'");
}
};
</script>
This is working on the page that was opened, but not on the page of the generated URL. I need to make it work in IF-ELSE statement. Something like
if(url contain word "something")
{
do that
}
So I need somehow pass generated url with href to script and then to if-else statement
You can check url pathname and then make control in your function
let pathname = window.location.pathname
if(pathname.includes('home'))
{
do that
}

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.

Add language suffix to url if it doesn't exist already (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');
});

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? :)

jQuery to find URI in codeigniter

I have a script that runs on every page of my codeigniter site.
jQuery(document).ready(function($) {
Cufon.replace('h1');
$('#term').hint();
setTimeout('changeImage()',9000);
});
I only want that last line setTimeout('changeImage()',9000); if I'm on the base url and there are no segments in the URI (only want this to run on my homepage).
Is this possible to do some type of if statement with jQuery and find out if there are no segments in the URI?
Thanks
Well you can do this with simple javascript using window.location, you have three things to worry about: pathname, search and hash, the code will be something like:
var win_location = window.location;
if ( win_location.pathname === "" || win_location.pathname === "/" && win_location.hash === "" && win_location.search === "")
{
// I'M HOME NOW DO SOMETHING
}
// hash will be for things like #anchor in the url
// search will be for things like ?param1=john&param2=doe
// so if you need those for some kind of dynamic handling on the home page remove the
// matching condition
use window.location
if ( window.location == YOUR_BASE_URL ) {
setTimeout('changeImage()',9000);
}

Categories