jQuery, active menu-item in menu-Navigation-bar - javascript

I have jQuery code that "colors the active menu item" in the my navigation menubar.
I found it online, and I find little of it hard to understand.
/// <reference path="jquery-1.10.2.js" />
$(document).ready(function () {
SetNavigation();
});
function SetNavigation() {
var pathName = window.location.pathname;
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$("#topnavnmenu a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.lenght) == href) {
$(this).closest('li').addClass("active");
}
})
}
Questions to the above displayed code:
Why is he doing that:
path = path.replace(/\/$/, "");
Should he not make sure before Comparison of Url and
that <a href = " " is taken before parameters
IF yes, how to write code for it ?
$("#topnavnmenu a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.lenght) == href) {
$(this).closest('li').addClass("active");
}
})

Why is he doing that: path = path.replace(//$/, "");
The regex \/$ in :
path.replace(/\/$/, "");
Used just to remove (replace by empty) the last slash / in the path.
Example :
console.log('www.website.com/'.replace(/\/$/, "")); //Remove last slash
console.log('www.website.com/page1/'.replace(/\/$/, "")); //Remove last slash
console.log('www.website.com/page2'.replace(/\/$/, "")); //No slash no change

Should he not make sure before Comparison of Url and that
Not 100% sure what u mean by this, but the way "he" has coded this if even if href or comparison is 'undefined' the execution will not stop.
Function simply gives active class to all matching menu items.
For the function it dosent matter if all or none match. Since function executed in document ready its safe to assume all href attributes are already existing and therefore they will be found.

Related

jQuery add class based on parent URL

on my homepage, I currently have a jQuery that adds a class (in this case an underline) to the link element. This works great and is based on comparing the url (url/firstsubmenu) in the browser with the href of the link element.
However as soon as I go to a child of that link element (url/firstsubmenu/secondsubmenu), the class is gone. I have tried to split the url so that the jQuery always looks for the parent but I just can't solve it. Can you help me?
Could it be solved by adding another code, like maybe "if (this).children().length > 0 ?"
Here is my jQuery:
var cururl = window.location.href;
cururl = cururl.split('#')[0];
jQuery("a.rs-layer").each(function(){
if(jQuery(this).attr('href')=== cururl){
jQuery(this).addClass("current-slider-menu");
}
});
EDIT: I am new to this, and I have tried so many different codes, googled for hours. I now know that I can only write JavaScript in my CMS. That is, I cannot use jQuery operators such as, for example, $.
Try this,
Change the class/selectors as per your requirement. This will add a unique class in the li element, now you can style this using css.
$(document).ready(function() {
$(".main_menu li").removeClass('current-slider-menu');
$(".main_menu li>a").filter(function(){
return this.href == location.href.replace(/#.*/, "");
}).parent("li").addClass("current-slider-menu");
});
You're definitely on the right track.
You can grab the currentURL (before the anchor #):
const currentURL = window.location.href.split('#')[0];
Then you can split the currentURL into its constituent folders:
const currentURLArray = currentURL.split('/');
Then, separately, you can grab all the myLinks:
const myLinks = [...document.querySelectorAll('a.rs-layer')];
And finally you can cycle through myLinks and if the name of the folder you want to match does match the name of the equivalent folder in the currentURL, then you can add the .current-slider-menu class:
for (myLink of myLinks) {
if (myLink.href.split('/')[1] === currentURLArray[1]) {
myLink.classList.add('current-slider-menu');
}
}
Complete Example:
const currentURL = window.location.href.split('#')[0];
const currentURLArray = currentURL.split('/');
const myLinks = [...document.querySelectorAll('a.rs-layer')];
for (myLink of myLinks) {
if (myLink.href.split('/')[1] === currentURLArray[1]) {
myLink.classList.add('current-slider-menu');
}
}
EDITED
try this
var cururl = window.location.href;
jQuery("rs-layer[id|='"+cururl.split('/')[3]+"'] , .rs-layer[href='"+cururl+"']").each(function(){
jQuery(this).addClass("current-slider-menu");
});
I solved it like this instead, skipping the whole idea with text-decoration.
I added an arrow. Finished.
JS:
var url = window.location.href;
var msg = document.getElementById('current-menu-item-arrow');
if( url.search( 'my-word' ) > 0 ) {
msg.style.display = "block";
}
CSS:
#current-menu-item-arrow {display:none;}

Match anchor tag with a specific href

I have a dashboard with a sidebar with navigation links where I highlight each link on the side once you go to the link. I match the link by doing this
$(function() {
var item = $('.sidebar-menu a[href="' + location.href + '"]');
item.parent().addClass('active');
});
But the problem is if you add an hash (#) to the address then it no longer matches the link. And I want it to match it regardless.
Currently it would match:
mysite.com/students/companies
But it wouldn't match:
mysite.com/students/companies#
mysite.com/students/companies/subpage
I want it to match anything that includes "mysite.com/students/companies"
I think you got problem because your anchor tag look something like that:
<a href='somethingelse.php'>Something Else</a>
I notice that you call parent div so.. you wrap your anchor tag by div or ul,li or something else..
What you can do simple add some extra data like 'data-user=''
so <div data-user='companies'><a href='somethingelse.php'>Something Else</a></div>
So now if somebody will be inside companies or something else just do the trick:
var url_string = window.location.href;
var url = url_string.split('/')
var item = $('div[data-user='+url[3]+']).addClass('active');
That will work for webpage look like:
www.some.com/companies
and
www.some.com/companies/sometihng
even
www.some.com/companies/sometihng/more
Have a try with
$('.sidebar-menu a').filter(function() {
return location.href.indexOf(this.href)!=-1;
}).parent().addClass('active');
var item = $('.sidebar-menu a[href*="' + location.pathname + '"]');

Extract characters after ?= in link

Can anyone see where I going wrong here, I'm trying to get the last characters after the ?p= in a link and put in a varaible, but the code I'm using returns /.
My code is:
$("#dvPartial").on('click', '.dvPagerCities a', function (event) {
alert('click detected');
var city = ($('input#hdnCountry').val());
alert(city);
var link = $('a').attr('href');
//var getEqualPosition = link.indexOf('?p='); //Get the position of '='
var getEqualPosition = link.indexOf('='); //Get the position of '='
var number = link.substring(getEqualPosition + 1); //Split the string and get the number.
My link is
»
I think what is happening is its picking up the 1st = .
My theory is this.
1) Detect the click event
2) Get the link that caused the event
3) Extract the value of p,
p can be 1 diget, 2 digets or 3 digets.
Any help would be appreciated, as it seems no sooner do I solve 1 problem then another arises.
Thanks
George
Assuming that p is the only parameter in the URL you can simply split by the = sign:
$("#dvPartial").on('click', '.dvPagerCities a', function (event) {
var city = $('input#hdnCountry').val();
var number = $(this).attr('href').split('=')[1];
});
The problem is this part:
var link = $('a').attr('href');
That does not select the link that was clicked, unless you happen to be clicking the very first link present in the HTML of the page. What that will do is select all <a> elements, then return the href attribute of the first one.
Inside your event handler, you want to use this to refer to the link that was clicked:
var link = $(this).attr('href');
// or simply
var link = this.href;
Try with this:
link.split('?p=')[1]
String s = "Jecy penny ? like sears";
String[] arr = s.split("\\?");
Added \\ before ?, as ? has a special meaning
String res = arr[0];
May be you are wrong at escape character for ' ? '
check this link Remove all characters after a particular character
Try this: http://jsfiddle.net/7atyG/1/
$(document).on('click', '.dvPagerCities a', function (ev) {
ev.preventDefault();
var link = $(this).attr('href');
var Linkval = link.substr(link.indexOf('=') + 1);
alert(Linkval);
});

How to get the text after the # symbol in a link?

I have a simple link with a hashtag in it. ie:
<a class="page_navigation" href="#something">click</a>
On clicking this, I would like to just end up with the 'something' part (minus the hash) in a var.
So far I have
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
});
Obviously I just end up with '#something' in my href var with the above code, and I understand I could do some kind of regex (not sure how yet) to strip the #, but I wonder if there is an easier way to access this part of the href I'm unaware of, without having to go through some find and replace code.
Any ideas?
Note: I also know I could store the 'something' in a data tag, but I'm trying to keep this code as DRY as possible.
If you know it has a # in it, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = this.href.replace(/^.*#/, "");
});
If you don't know whether it has one it it or not, you can use this:
$('.page_navigation').click(function(e)
{
e.preventDefault();
var hash = "";
if (this.href.indexOf("#") {
hash = this.href.replace(/^.*#/, "");
}
});
In HTML5, you could use:
this.hash
but that is only for the latest browsers.
var theHash = $(this).prop("hash").substr(1);
Related answer to another question
Demo http://jsfiddle.net/UR3XN/
code
$('.page_navigation').click(function(e)
{
e.preventDefault();
var href = $(this).attr('href');
var equalPosition = href.indexOf('#'); //Get the position of '#'
var withouthash = href.substring(equalPosition + 1);
alert(withouthash);
});​
You don't need regular expressions for this. You can simply do
var fragment;
if (window.location.hash) {
fragment = window.location.hash;
}
Note that this will pick up the # symbol as well. So,
fragment = "#something"
If you don't want the # symbol, use substring like this:
fragment = window.location.hash.substring(1)
If you want to pick out the hash fragment from an anchor tag, you can do this:
var link = $('#yourAnchor').attr('href');
var fragment;
if (link.indexOf("#") !== -1) {
fragment = link.substr(link.indexOf("#") + 1);
}

Javascript Error: this.replace($foo, "");

My sixth line of code does not work. Please help.
function ajax() {
$('a[class="ajax-cw"]').click( function() {
$('#cw').load( this + "?ajax" );
$('#nav li.current').removeClass('current');
var $base = $("base").attr("href"),
$link = this.replace($base, ""); //Line does not work
alert ($link);
return false;
});
};
if you were trying to replace parts of the href contents of the currently clicked link with that of the base object, you have to access the href contents via
var currenthref = $(this).attr('href');
and then use currenthref in the replace line.
$link = currenthref.replace($base, "");
Thre replace function on this will not properly work because it is not a string but rather an object (most likly jquery) that represents the link element you klicked on.
try this:
this.href.replace($base, '');
this in line 6 is the <a /> tag, not the href of that tag. $(this).attr('href').replace($base,"") will perform better.
You need to end the previous line with a semi-colon. You have ended it with a comma.
var $base = $("base").attr("href");

Categories