Skip to content

Instantly share code, notes, and snippets.

@xinthink
Created May 20, 2013 10:35
Show Gist options
  • Save xinthink/5611526 to your computer and use it in GitHub Desktop.
Save xinthink/5611526 to your computer and use it in GitHub Desktop.
bootstrap navbar auto activation in coffeescript
# get relative path of URL
getPath = (url) ->
path = url.split(window.location.host)[1] or '/'
path + if path.match '/$' then '' else '/' # ensure endsWith '/'
# check whether p is parent of path (starts with)
parentOf = (p, path) ->
unless p is '/' then path.match '^' + p
else p == path # '/' should not matches any path
$(document).ready ->
path = getPath document.URL # get current path
# activates current path, excluding dropdown-menu
$('.nav li a').not('.dropdown-menu a').each ->
navPath = getPath this.href
if parentOf navPath, path
$(this).closest('li').addClass 'active'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment