I’m curious to know people’s preferences…
I’ve recently gone head-first into jQuery and I am loving it. However, I’m finding that I’m replacing a lot of (somewhat trivial) backend (tech: ASP.NET) functions with tiny jQuery functions. For instance, rather than assign a navigation button as a back-end control and change its class when its page is landed on (ie, highlight the “about” button when on the about us page), I simply parsed the URL and added a class to the button:
var pathname = window.location.pathname;
if (pathname == "/about/") {
$("#nav-about").addClass("selected");
}
Solutions like these seem rather simple (maybe too simple), but I am always wary to rely too heavily on JavaScript. Does anyone else do similar things to this, and if so, how do you maintain code like this? How do you know where to strike the balance between good ol’ trusty server code that works every time and fast, fancy, shiny jQuery that works pretty much every time, except when the user may have JavaScript turned off?
EDIT
I’m not really speaking of this particular instance… I’m talking about little enhancements like this. What is the line you draw when it comes to jQuery enhancements or just do it on the server? Thanks 🙂
My past few projects I have had the luxury of knowing that 100% of the users would have Javascript enabled. In that case, I actually did something very similar to what you have to save myself from having to highlight the current page in the navigation server-side.
Without that luxury, however, I consider shortcuts like this to be “pushing it” as far as using jQuery – sure, you can just say “if they have Javascript disabled, then they just won’t see the navigation page highlighted, it’s not a big deal” – while that may be true, it is a big deal to have the mentality to shun a more robust, reliable way of doing it server-side for no particularly good reason. It is important to stop yourself short of replacing battle-tested server-side solutions with “easier” code in the client. It is tempting, but not always the best thing for your project and your users, some of which will have JS disabled and may look at the navigation wondering where they are and find themselves “lost”.
All in all, I would recommend you switch back to server-side code for this one. There’s just no need to throw it away.