Reputation: 25
I need to change the appearance of a link from a menu if it belongs to the current URL. I don't know how I can detect current URL and change a element class.
I would use jQuery
Upvotes: 0
Views: 212
Reputation: 74738
What you can do is
.indexOf('.html')
(Or your extension).substr(url.lastIndexOf('/'))
(this will give you the page name)class
selector or id
selectoractive
class to that link on page loadHow this will go see below:
lets suppose this is your url : http://localhost/myWebsite/index.html
$(function(){ // this is done on doc ready function
var url = window.location;
var dUrl = url.substr(0, url.indexOf('.html'));
var link = dUrl.substr(dUrl.lastIndexOf('/')+1);
$('#'+link).addClass('active'); // on page load this will add the class to the corresponding link
});
you can try this demo: http://jsfiddle.net/K9YAz/
Upvotes: 2
Reputation: 33875
You could use the properties of window.location
to get the URL, or the parts of the URL that you need, of the current page. You could then select every anchor of the menu, loop over them, compare the value of their respective href-attributes with the URL of the current page. If they are equal, you add the proper class to the element.
Upvotes: 1
Reputation: 2799
$( document).ready(function (){
$( function(){
var url = window.location.pathname,
urlRegExp = new RegExp(url.replace( /\/$/,'' ) + "$" );
$('a').each( function(){
if(urlRegExp.test(this .href.replace(/\/$/, ''))){
$( this).addClass('active' );
}
});
});
});
Upvotes: 2