BarryChuckle Posted October 17, 2011 Share Posted October 17, 2011 Hey guys be easy on me it's my first post Okay I've attached some code which I done earlier. I'll explain it first - I have a header which is included throughout each of the pages on my website. When a page is selected the header is then given the class selected to change the style to show the current page is selected. I have a terrible feeling that there is a bette way of coding this.. I am not sure though because I am not that experienced. It works but it's terribly messy (It runs when the page has loaded .read() switch(document.title){ case('link1'): $('#1').addClass('selected'); break; case('link2'): $('#2').addClass('selected'); break; case('link3): $('#customers').addClass('selected'); break; default: $('#1').addClass('selected'); } So is there a better way of getting this to work ? Also is there any cool articles that can help me improve my coding (I can generally get things to do what I want but with very shoddy code imo. Thanks again guys! Quote Link to comment https://forums.phpfreaks.com/topic/249292-better-way-of-coding-this/ Share on other sites More sharing options...
requinix Posted October 18, 2011 Share Posted October 18, 2011 You mean besides with a switch? var lookup = { "link1": "#1", "link2": "#2", "link3": "#customers" }; var selector = lookup[document.title] || "#1"; $(selector).addClass("selected"); Quote Link to comment https://forums.phpfreaks.com/topic/249292-better-way-of-coding-this/#findComment-1280084 Share on other sites More sharing options...
BarryChuckle Posted October 18, 2011 Author Share Posted October 18, 2011 Thanks, is the use of the switch statement okay ? Sorry I am not that great at coding (or not very confident) I appreciate your reply. Quote Link to comment https://forums.phpfreaks.com/topic/249292-better-way-of-coding-this/#findComment-1280089 Share on other sites More sharing options...
Adam Posted October 18, 2011 Share Posted October 18, 2011 Using an object as requinix suggested would reduce the duplicated code within your switch and keep it easy to maintain. Quote Link to comment https://forums.phpfreaks.com/topic/249292-better-way-of-coding-this/#findComment-1280166 Share on other sites More sharing options...
BarryChuckle Posted October 18, 2011 Author Share Posted October 18, 2011 Thanks for the reply Adam. I will remember this thread. Quote Link to comment https://forums.phpfreaks.com/topic/249292-better-way-of-coding-this/#findComment-1280291 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.