Is there a code snippet that can detect the current user's page and then add <a class="active">
to an item in a ul
(my menu). I am making a tumblr theme and they do not allow PHP (I usually add <?php if ( $current == "home" ) { echo "class='active'" } ?>
in my menu and $current = "home"
on my pages) and they do not have a standard (such as current_page_item) so I need to do this with javascript (or jQuery) only. Is it possible?
views:
21answers:
1
A:
It's not possible with HTML only but should be straight forward with JQuery, and just a bit harder with javascript only.
Here is a solution relying on JQuery and URL parser plugin: assuming you have the information you need in the file name (e.g: page1.html refered by id="page1")
$(document).ready(function() {
var pathname = window.location.pathname;
var page = jQuery.url.attr('file').replace(".html", "");
$('#' + page).addClass("active");
});
Damien
2010-09-14 02:36:15
Sorry. I'm not that great with jQuery. How do I get that to detect my pages?
Christopher
2010-09-14 21:29:25
You need to download jQuery and URL plugin and reference them in your HTML header like this:<script type="text/javascript" src="js/jquery.js" /><script type="text/javascript" src="js/jquery.url.js" /> then the code I gave you should detect the current page.
Damien
2010-09-14 21:52:31
Will it detect it as-is or do any changes need to be made?
Christopher
2010-09-14 22:56:06
attr('file') will detect the filename in the URL, I don't know if it's suitable in your case. You may have to rework the script. Check the documentation of the URL parser plugin and try it.
Damien
2010-09-15 02:24:28