I have a web application that I'm developing in Django. I wnat to have a simple way to track where the user is on the site. So I thought I would change the css of the item clicked on the menu.
I added this simple piece of code.
<script type="text/javascript">
$(document).ready(function(){
$(".up_menu_item").click(function(){
$(this).addClass("green");
var excludeThis = $(this);
$(".up_menu_item").not(excludeThis).each(function(){
$(this).removeClass("green");
});
});
});
</script>
When I click on the menu item, the color changes, but it turns back to default right after. The item I click on are actually tags which redirect the user to another url. But the menu (and the javascript) is always included in the urls called, so I thought the class would stay.
I don't know if I'm very clear, but I would appreciate any help as this is starting to drive me crazy!
Javascript isn't the appropriate tool for this. As Kim says in the comment, when you reload the page, your class won't be present any more.
Since you're using Django, the way to do this is in the Django template - for each url in your menu, check if it matches the current URL, and add the class if so.
Edit You can get the current URL from request.path, assuming you've passed the request into your template (this happens automatically if you've enabled the request context processor).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With