patternhtmlMinor
Simple CoffeeScript navigation menu
Viewed 0 times
coffeescriptmenusimplenavigation
Problem
I'm using simple script to handle tab menu like this:
HTML:
and CoffeeScript:
This code works, but i'm pretty sure that it's very far away from best practices, and can be greatly improved, as these are my first tries in CoffeeScript. So the question is, can this code be beautified in some way?
HTML:
Info
Orders
Models
Balance
and CoffeeScript:
jQuery ($) ->
class Nav
constructor: (@elements) ->
self = @
wHash = document.location.hash.replace("#", "") or "info"
# activate element by location hash
@.activate document.getElementById "personal-#{wHash}"
# bind element activation on click
elements.click ->
self.activate @
activate: (elem) ->
@elements.removeClass "active"
$(elem).addClass "active"
# set a proper hash
wHash = elem.id.split("-")[1]
document.location.hash = "##{wHash}"
# load proper content into an inner section
# it works very fast and is the reason i use this type of navigation in the first place
$("#personal-content").load "/user/#{wHash}"
new Nav $("#personal").find("li")This code works, but i'm pretty sure that it's very far away from best practices, and can be greatly improved, as these are my first tries in CoffeeScript. So the question is, can this code be beautified in some way?
Solution
You're building a navigation, however there are no links. It's highly recommended to use
Your naming is a bit loose. What is personal in your context? Please specify that. Even something like
I've changed your markup a bit to reflect my small suggestions. Note that I changed the ID's from your list items to classes. ID's are only for elements which will occur only once a page in any situation. You can't say that for sure for single navigation items.
anchor tags for linking purposes.Your naming is a bit loose. What is personal in your context? Please specify that. Even something like
personal-navigation is quite loose, but still better.I've changed your markup a bit to reflect my small suggestions. Note that I changed the ID's from your list items to classes. ID's are only for elements which will occur only once a page in any situation. You can't say that for sure for single navigation items.
Info
Orders
Models
Balance
Code Snippets
<nav id="personal-navigation">
<ul class="clearfix">
<li class="personal-info"><a href="#">Info</a></li>
<li class="personal-orders"><a href="#">Orders</a></li>
<li class="personal-models"><a href="#">Models</a></li>
<li class="personal-balance"><a href="#">Balance</a></li>
</ul>
</nav>
<div id="personal-content"></div>Context
StackExchange Code Review Q#41329, answer score: 7
Revisions (0)
No revisions yet.