Created
February 27, 2018 13:20
-
-
Save isrd1/6de837a34ad960a23076ff7815ac2957 to your computer and use it in GitHub Desktop.
Highlights any menu item which links to the current page and deactivates it. Use it by adding ROB.utils.setCurrentPageActive()
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @author Rob Davis | |
* @licence CC-BY | |
*/ | |
var ROB = ROB || {}; | |
/** | |
* create an IIFE which extends a 'ROB' module if it already exists and creates | |
* a submodule called 'utils'. | |
*/ | |
ROB.utils = (function (oldModule) { | |
"use strict"; | |
const returnObject = oldModule; | |
/** | |
* Gives the current filename of the url or index.html if no name (this is less | |
* than perfect since giving just a path might mean index.html, index.php for instance | |
* | |
* @method getCurrentPageName | |
* @returns the filename of the current url or index.html if there is no filename | |
*/ | |
const getCurrentPageName = function () { | |
let pagePathName= window.location.pathname; | |
return pagePathName.substring(pagePathName.lastIndexOf("/") + 1) || 'index.html'; | |
}; | |
/** | |
* changes the link of the current page to make it void add adds a class | |
* called active to it, this is prevent a menu linking to the current page from | |
* being doing anything. | |
*/ | |
returnObject.setCurrentPageActive = function (menuLinkParent, activeClassName) { | |
menuLinkParent = menuLinkParent || 'nav'; | |
activeClassName = activeClassName || 'current'; | |
let pn = getCurrentPageName(), | |
currentLink = document.querySelector(`${menuLinkParent} a[href="${pn}"]`); | |
if (currentLink) { | |
currentLink.setAttribute('href', 'javascript:void(0)'); | |
currentLink.classList.add(activeClassName); | |
} | |
}; | |
return returnObject; | |
}(ROB.utils || {})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you want a simple version, not inside an object wrapper using the extending module pattern, then you can use this:
and then you can call it, perhaps like: