Set selected navigation option using window.location - javascript

I have a theme that sets the selected left navigation option based on what URL you are visiting. However, it breaks if the is a variable attached to the URL, for example www.test.com/abc.aspx?delete=1. The URL www.test.com/abc.aspx works fine and sets the link ABC to active.
I have tried to modify the code to cut off everything after and including ?, but it won't work as intended (nothing in the NAV is selected).
ORIGINAL CODE:
$(function () {
var url = window.location;
var element = $('ul#sidebarnav a').filter(function () {
return this.href == url;
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});
MY EDITED CODE:
$(function () {
var url = window.location.toString();
var url_fix = url.split('?');
var element = $('ul#sidebarnav a').filter(function () {
return this.href == url_fix[0];
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});
I think it is the line with "return this.href == url_fix[0];" that is the culprit.
SOLUTION (what I came up with after reading the comments, thanks guys):
$(function () {
var url = location.href.split("/").slice(-1).toString();
var url_fix = url.split('?');
var element = $('ul#sidebarnav a').filter(function () {
return $(this).attr("href") == url_fix[0];
}).addClass('active').parent().addClass('active');
while (true) {
if (element.is('li')) {
element = element.parent().addClass('in').parent().addClass('active');
}
else {
break;
}
}
});

Try comparing pathnames instead.
var element = $('ul#sidebarnav a').filter(function () {
return this.pathname == location.pathname;
}).addClass('active').parent().addClass('active');
For example on this page location.pathname returns:
"/questions/48234042/set-selected-navigation-option-using-window-locaiton/48234196"
and does not include location.hash or location.search

I used the answer by #vbguyny to solve the issue. Had to add location.href.split("/").slice(-1).toString(); to get the actual page name, but after that it worked fine. Thanks!

Related

jQuery check if URL contains string

I have this code
events.on('loaded', function() {
$('.server_details .start button').click();
});
but I only want it to run if the end of the URL is &autoconnect, can someone show example of how to do this?
Example URL http://www.example.com:7778&autoconnect
You can get the url with window.location.href
and then check that using indexOf:
events.on('loaded', function() {
if (window.location.href.indexOf("&autoconnect") > -1) {
$('.server_details .start button').click();
}
});
You say "I only want it to run if the end of the URL is &autoconnect"
I say
var url = 'http://www.example.com:7778/&autoconnect';
var param = '&autoconnect';
var valid = url.indexOf(param) == url.length - param.length;
If there is a possibility that there may be other parameters as well...
var url = 'http://www.example.com:7778/&autoconnect&alsovalid';
var param = '&autoconnect';
var valid = url.indexOf(param) >= 0;
This would be more correct I suppose.
$(window).on('load', function () {
if (window.location.href.indexOf('url-content') > -1) {
// Your function do be executed
}
});

Go To Anchor on Load ( if else statement)

Hi I have a page that navigates using anchors. On load the index page (A) needs to jump to anchor. Fine I can do this with on load function but coming back to the page A from page B I want to jump to a different anchor. I have this working:
<!-- go to Anchor -->
<script type="text/javascript">
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#top") > -1){
window.location.hash="top";
} else {
window.location.hash="middle";
}
}
</script>
#middle is the anchor to use when coming from a link that contains no anchor (or from typing the address into the url bar). I want to add three more 'if's'. I am fairly new at js so bear with me if I am doing something silly. I tried this:
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#right") > -1){
window.location.hash="right";
} else {
window.location.hash="middle";
}
if(urllocation.indexOf("#bottom") > -1){
window.location.hash="bottom";
} else {
window.location.hash="middle";
}
if(urllocation.indexOf("#left") > -1){
window.location.hash="left";
} else {
window.location.hash="middle";
}
But not joy, the js breaks and no longer goes to #middle on page load.
I tried a wild card approach:
function goToAnchor() {
var urllocation = location.href;
if(urllocation.indexOf("#.") > -1){
window.location.hash=".";
} else {
window.location.hash="middle";
}
}
Again, no joy.
Any help please.. thanks kindly
I am not quite sure I understand the effect you are trying to achieve (since window.location.hash should already contain the hash part of your url), but your code should probably rather be
function goToAnchor() {
var urllocation = location.href;
if (urllocation.indexOf("#right") > -1) {
window.location.hash = "right";
} else if (urllocation.indexOf("#bottom") > -1) {
window.location.hash = "bottom";
} else if(urllocation.indexOf("#left") > -1) {
window.location.hash = "left";
} else {
window.location.hash = "middle";
}
}
I am also guessing that your 'wild card' approach is meant to use regular expressions:
function goToAnchor() {
var urllocation = location.href;
var hashMatch = urllocation.match(/#(.*)/)
if (hashMatch){
window.location.hash = hashMatch[1];
} else {
window.location.hash = "middle";
}
}
Again, I don't quite see what effect this code should have, since window.location.hash will probably have the same value before and after the assignment.
If you just want to go back to the hash in the URL, have you tried something like this?
var hash = window.location.hash || "middle"; //Get current hash or default to "middle" if no hash is currently set
window.location.hash = +new Date() + ""; //Remove the hash and set it to some random value
window.location.hash = hash; //Set to the old hash

How to dynamically change the anchor tag link?

I'm trying to remove a landing page when I click on a link on a page. The page isn't mine so I'm trying to change the href with a user script.
Without any modification, the link looks like this:
https://www.domain.com/out.php?u=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DPUZ1bC-1XjA%26amp%3Bfeature%3Drelated
What I want:
http://www.youtube.com/watch?v=PUZ1bC-1XjA&feature=related
What I got so far:
http://www.youtube.com%2fwatch%3fv%3dpuz1bc-1xja%26amp%3bfeature%3drelated/
But that adress doesn't work in the browser.
This is my current code:
$('a').each(function(index) {
var aLink = $(this).attr('href');
if(aLink) {
if(aLink.indexOf("out.php?u=") > 0) {
aLink = aLink.substring(51);
console.log(aLink);
$(this).attr('href', "http://"+aLink);
console.log($(this).prop('href'));
}
}
});
All help and tips are appreciated.
You need to decode the URL using decodeURIComponent
Change:
$(this).attr('href', "http://"+aLink);
To:
$(this).attr('href', 'http://' + decodeURIComponent(aLink));
Take a look at decodeURIComponent
You can also make use of the hostname, pathname, and search parameters of anchor elements.
// general function to turn query strings into objects
function deserialize_query_string(qs) {
var params = {};
var fields = qs.split('&');
var field;
for (var i=0; i<fields.length; i++) {
field = fields[i].split('=');
field[0] = decodeURIComponent(field[0]);
field[1] = decodeURIComponent(field[1]);
params[field[0]] = field[1];
}
return params;
}
$(document.links).each(function(i){
if (this.hostname=='www.domain.com' && this.pathname=='/out.php') {
var params = deserialize_query_string(this.search);
if (params.u) {
this.href = u;
}
}
});

Match url folders with a tag href to make an active state

I made an active state for my menu on a certain urls. I have urls like this:
/products/other-clothing/sporting/adults-anzac-australia-polo
/products/other-clothing/sporting/adults-nz-tee
/products/bags/backpacks
My code gets the folder from after the / so other-clothing, sporting, etc.
It is working fine, I just assume there is a more efficient way to write the code.
Here is my code:
jQuery(".product-nav li a").each(function() {
// URL url
var cat = location.pathname.split("/")[2];
var subcat = location.pathname.split("/")[3];
var c = "/products/" + cat + "/" + subcat;
// A tag url
var acat = this.href.split("/")[4];
var asubcat = this.href.split("/")[5];
var e = "/products/" + acat + "/" + asubcat;
if(e == c) {
jQuery(this).parent().addClass("active");
jQuery(this).parent().parent().parent().addClass("active");
}
});
If anyone can provide a cleaner way of writing the code that'd be great. I probably dont need "/products/" +.
Notice the output of the following expressions:
$('')[0].href;
/*
* http://stackoverflow.com/questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state
*/
$('').eq(0).attr('href');
/*
* /questions/7564539/match-url-folders-with-a-tag-href-to-make-a-active-state
*/
So, if your <a> tags contain URLs that start with / then you can compare the .attr('href') with location.pathname. For testing, try running this in console from this page:
$('a').each(function () {
if ($(this).attr('href') == location.pathname) {
$(this).css({
'font-size': '40px',
'background-color': 'lime'
});
}
});
Here's a brief whack at it:
jQuery(".product-nav li a").each(function() {
// URL url
var c = location.pathname.split('/').slice(2, 4)
// A tag url
, e = this.href.split('/').slice(4, 6)
;
if(e[0] == c[0] && e[1] == c[1]) {
jQuery(this).parentsUntil(
'div:not(.subnav)', // go up the tree until the 1st div that isn't .subnav
'.product-nav li, .subnav' // and only match these parents
).addClass('active');
}
});
.parent().parent().parent()... has a pretty bad code smell to it but can't be improved without a look at your markup. You should probably be using .closest() instead.
Interesting question. Here is my attempt to clean it up:
jQuery(function ($) {
function Category(outer, inner) {
this.outer = outer
this.inner = inner
}
Category.fromURL = function (url) {
var parts = url.replace(/^(https?:\/\/.*?)?\//, "").split("/")
return new Category(parts[1], parts[2])
}
Category.prototype.equals = function (other) {
return this.outer === other.outer
&& this.inner === other.inner
}
var category = Subcategory.fromURL(location.href)
$(".product-nav a").each(function () {
if (Category.fromURL(this.href).equals(category)) {
$(this).closest("li.inner").addClass("active")
$(this).closest("li.outer").addClass("active")
}
})
})

Check url for particular string using jquery

$(document).ready(function () {
var loc = window.location.hostname;
alert(loc);
if (loc = "xyzvalue.com") {
//do some operation
}
});
I am using above jquery to get current url in jquery.Alert will show xyzvalue.com as popup. Now I want to check for "value" string in xyzvalue.com.
if (loc = "xyzvalue.com") {
should be
if (loc == "xyzvalue.com") {

Categories

Resources