Javascript switch statement with a substring
I needed to set an active tab in a menu. You obviously can not do this with pure css, at least that I have found. I am using ASP.Net MVC so the url will always display what page I am on. What was really cool is that I could do this all in Javascript. I have done this before, but needed to test for a substring within the URL. Here is what I did:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 | $(document).ready(function () { var n = document.URL.toLowerCase(); test(n); }) function test(str) { switch (true) { case /admin_doclink/.test(str): $("#admin_doclink").addClass("active"); break; case /admin_directory/.test(str): $("#admin_directory").addClass("active"); break; case /doclink/.test(str): $("#doclink").addClass("active"); break; case /directory/.test(str): $("#directory").addClass("active"); break; } } |
What I didn’t realize is that the function actually needs to be named “test”. I tried different names and would get an error message stating that the function didn’t exist in RegExp. Once I named it “test” the error went away. If someone could explain this one to me I would be grateful.