Russell
Russell

Reputation: 69

"Active" class only sets when using extension for page

I am attempting to make my nav bar automatically have the active class if it's on the page matching the nav bar... the other issue although is that I have URL rewriting on with htacess, nothing big, just removing the file extension for neatness.

The only way the following code works is when I use the url with the extension.

var url = window.location.href;
$('ul.tdsnav a[href="' + url + '"]').parent().addClass('active');
$('ul.tdsnav a').filter(function() {
    return this.href == url;
}).parent().addClass('active');

What I mean by that is... MySite.com/index.php - The nav item for home turns active MySite.com/index - The nav item stays in active

I have also tried the following, but it didn't seem to work...

function getBaseName(url) {
        if (!url || (url && url.length === 0)) {
            return "";
        }
        var index = url.lastIndexOf("/") + 1;
        var filenameWithExtension = url.substr(index);
        var basename = filenameWithExtension.split(/[.?&#]+/)[0];

        // Handle '/mypage/' type paths
        if (basename.length === 0) {
            url = url.substr(0, index - 1);
            basename = getBaseName(url);
        }
        return basename ? basename : "";
    }

    var url = window.location.href;
    var url2 = getBaseName(url);
    $('ul.tdsnav a[href="' + url2 + '"]').parent().addClass('active');
    $('ul.tdsnav a').filter(function() {
        return this.href == url2;
    }).parent().addClass('active');

Any help would be appreciated.

Edit:

The Html:

<div class="sidebar" id="sidebar">
<div class="sidebar-inner slimscroll">
    <div id="sidebar-menu" class="sidebar-menu">
        <ul class="tdsnav">
            <li class="menu-title">
                <span>Main</span>
            </li>
            <li>
                <a href="index.php"><i class="fe fe-home"></i> <span>Dashboard</span></a>
            </li>
        </ul>
    </div>
</div>
</div>

Upvotes: 0

Views: 42

Answers (1)

Max
Max

Reputation: 519

You can try using the "Starts with Selector": https://api.jquery.com/attribute-starts-with-selector/ so you don't have to fully match the URL, just the beginning without the extension.

Something like this:

function getBaseName(url) {
        if (!url || (url && url.length === 0)) {
            return "";
        }
        var index = url.lastIndexOf("/") + 1;
        var filenameWithExtension = url.substr(index);
        var basename = filenameWithExtension.split(/[.?&#]+/)[0];

        // Handle '/mypage/' type paths
        if (basename.length === 0) {
            url = url.substr(0, index - 1);
            basename = getBaseName(url);
        }
        return basename ? basename : "";
    }

    var url = window.location.href;
    var url2 = getBaseName(url);
    $('ul.tdsnav a[href^="' + url2 + '"]').parent().addClass('active');

Upvotes: 0

Related Questions