java - Add Active Class to Selected Page (With and Without Trailing Slash) -


i've got selector adding "active" class selected page. working trailing slash, e.g. if its:

site.com/test/ works fine.

however if site.com/test doesnt.

this causing issues when using "back" button takes me page without trailing "/"

here code:

$(document).ready(function () {     $('a[href="' + this.location.pathname + '"]').parent().addclass('active'); }); 

can amend add class both variations? also, if possible can amended adds active class parent, if select childpage of parent?

e.g. site.com/test/edit test set active.

thanks

str.replace(/\/+$/,'') + '/' make sure string ends /, code this:

$(document).ready(function () {     str = this.location.pathname.replace(/\/+$/,'') + '/';     $('a[href="' + str + '"]').parent().addclass('active'); }); 

if don't know if links end slash, can check everything:

$(document).ready(function () {     str1 = this.location.pathname.replace(/\/+$/,'') + '/';     str2 = this.location.pathname.replace(/\/+$/,'');     $('a[href="' + str1 + '"], a[href="' + str2 + '"]').parent().addclass('active'); }); 

edit

let's try selecting parent links:

var tmp = this.location.pathname.replace(/.*?:\/\//g, "").replace(/\/+$/,''); arr = tmp.split('/'); while(arr.length > 1) {   tmp = 'http://' + arr.join('/');   $('a[href="' + tmp + '"], a[href="' + tmp + '/"]').parent().addclass('active');   arr = arr.slice(0,-1); } 

basically removing http:// beginning , splitting string array elements on every /. removing end elements 1 one, gluing again , constructing selector accordingly.

here in action, how generates links:

$('#test').click(function(){        // replaced string input value testing    var tmp = $('input').val().replace(/.*?:\/\//g, "").replace(/\/+$/,'');    arr = tmp.split('/');        // clearing output here    $('div').html('');    while(arr.length > 1) {      tmp = 'http://' + arr.join('/');            // appending current result      $('div').append('<p>' + tmp + '/</p>');      $('a[href="' + tmp + '"], a[href="' + tmp + '/"]').parent().addclass('active');      arr = arr.slice(0,-1);    }  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>  <input value="http://google.com/sub1/sub2">  <button id="test">test</button>  <div></div>


Comments

Popular posts from this blog

toolbar - How to add link to user registration inside toobar in admin joomla 3 custom component -

linux - disk space limitation when creating war file -