Just dumb man try talk about code.

Wednesday, July 6, 2016


If you have build some web application with complex route, modify how some menu item active dynamically can be complicated. But, that was old story, we now live at the world where so many tools we can use to build any apps. The PHP framework like YII or CodeIgniter have awesome feature to solve any problems and offer you capability to rapid development.

Go back to topic, assume you have build your apps well organized and you wanna make small modification on menu item. One menu item should be active as users request another location (URL). Because this case categorized as front end case, i choose to use javascript to handle user action. Javascript is powerful language that have rich feature to manipulate DOM document.

Before code, following requirements must be fulfilled:
  1. The web apps have proper route.
    Every request to page, sub-page and post must be accessed as absolute URL. For example:
    http://www.example.com/page1/post_title
    http://www.example.com/page1?title=post_title

  2. The URL which used to refer on specific page by click menu item is not query formed.
    For example, the url go to "News" page should be look like:
    www.example.com/news
    But, should not like:
    www.example.com?page=news

  3. Each menu item has id that match with provided route segments.
    Assume the menu is ul list, so the menu markup should look like:
    <ul class="dropdown-menu">
        <li id="page1"><a href="#">page1</a></li>
        <li id="page2"><a href="#">page2</a></li>
    </ul>
    
If all requirements above have fulfilled, it's time to solve the problem:
  1. Catch the full URL path.
  2. Get only the last URL segment.
  3. Change class attribute of menu item which has id match with last URL segment.
Finally, the code should look like:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/** Active Menu Item Switcher
 * 
 * Goal: Activate menu item which have id match with last url segment. 
 */

// Initialize the current url and path
window.onload=function() {
 var curUri = window.location.href;
 var pathUri = window.location.pathname;

 console.log("path uri: "+pathUri); // Checking got the pathname
 var path = pathUri.split("/");

 console.log("last uri: "+path[path.length-1]); // Checking got the last url segment
 setAtcive(path[path.length-1]);
}

// Activate menu item by last url segment
function setAtcive(id) {
 var target = document.getElementById(id); // Filter menu item id that match with last url segment
 if (target !== null) {
  target.classList.add("active"); // Activate matched menu item
 } else {
  document.getElementById("home").classList.add("active"); // Else, activate "Home" menu
 }
}

,

0 comments :

Post a Comment

Powered by Blogger.

Followers