javascript - Is link pointing to this page? -
for website's navigation want give links current page color.
how find links pointing current page?
link's href
"../index.php" current page http://mysite.myserver.com/index.php.
this current approach, doesn't want work:
string.prototype.endswith = function(str) { return ( this.match(str + "$") == str ); } string.prototype.startswith = function(str) { return ( this.match("^" + str) == str ) } string.prototype.trim = function(sec) { var res = this; while (res.startwith(sec)) { res = res.substr(sec.length); } while (res.endswith(sec)) { res = res.substr(0, res.length - sec.length); } return res; }
and, when document ready:
$("a").each( function (i) { if (window.location.pathname.endswith($(this).attr("href").trim("."))) { $(this).addclass("thispage"); } } );
and yes, know might color home link (../index.php - because pages end that!). that's why need better way...
$("a[href]").filter(function() { return window.location.pathname === this.pathname; }).addclass("thispage");
regarding comment, if window.location directory, can create string ends index.php
.
var win = window.location.pathname; if( win.slice(-1) === '/' ) { win += 'index.php'; } $("a[href]").filter(function() { return win === this.pathname; }).addclass("thispage");
Comments
Post a Comment