WordPress-Christmas-2010-18

Category And Archive Dropdown With Unobtrusive JavaScript

A good website works when a user comes along with JavaScript disabled, just as well as with scripting enabled. You separate the JS layer of the site from anything else (and waived for example, onclick in HTML) and places the scripts in a way that only improves the already existing functionality of the site. So the visitors can navigate through the website with and without JS, even though it might be a little more difficult or less attractive without scripting. This approach to scripting on sites is called Unobtrusive JavaScript. Jenn Lukas gives in this talk at the JSConf 2010 reasons why it's a good thing. Besides all the good reasons, the main argument for unobtrusive JavaScript that is to be implemented with appropriate planning so easily that it would be a wasted potential if you would without it. The problem can be alone if the used CMS makes problem - which brings us to WordPress.

Occasionally you like to have in your blog sidebar drop down menus (select-elements) to navigate the categories and the archive and the WordPress Codex provides the documentation and appropriate solutions for archive in which, however, both with only activated JavaScript function. In both cases, the URL of the destination page is stored in the value-value of the built-in option elements of the drop-down menu and when you select an entry, you will be forwarded via JavaScript on the very URL. The almost same functionality could be achieved also without scripts:

  1. Create an old-fashioned GET form with submit button that sends to the base address of the site
  2. Put the select in this very form and specify name="cat"
  3. Give the option elements the slug of the categories

Submitting the form will result in a call to blog.de/?cat=category and thus the desired category, possibly with a redirect to the search engine friendly version of the URL. This works for the visitors just as good as the solution of the Codex, leaving aside the fact that you have to click on a button. But this is where you can engage with JavaScript to hide the button and sending the form via, by a script inserted, onclick handle . The end result looks like the script for users with Codex solution and all others come then just by clicking on the button to its destination and everyone is happy. So let's get to work!

The basis for the category drop forms creates a normal HTML form:

<form id="kategorienform" action="<?php bloginfo('url'); ?>" method="get">
    <label for="kategorienselect">Jump to Category</label>
    <select id="kategorienselect" name="cat">
        <option value="">-- Please Select</option>
        <?php
            $categories = get_categories('hierarchical=0');
            foreach($categories as $category){
                $selected = (is_category($category->cat_ID)) ? 'selected' : '';
                echo '<option '.$selected.' value="'.$category->cat_ID.'">'.$category->cat_name.' ('.$category->count.')</option>';
            }
        ?>
    </select>
    <input id="kategorienbutton" value="Kategorie abrufen" type="submit">
</form>

You could use this in your side bar and it would work, but we still want to get rid of the submit button and start forwarding directly when selecting a category. For this purpose, it does not take more than 6 lines of JavaScript that can be inserted directly below the form:

<script type="text/javascript">
    document.getElementById('kategorienselect').onchange = function(){
        if(this.value){
            document.getElementById('kategorienform').submit();
        }
    };
    document.getElementById('kategorienbutton').style.display = 'none';
</script>

If the user changes his selection in select element, is (if not the entry "Please select" is selected) submitting the form automatically, without having to activate the with style.display = 'none' made invisible button - done is the most user-friendly and still working without JavaScript category dropdown! This is a bit more code than the three lines from the Codex, but it works guaranteed on every visitor. And the principle is quite simple, provided you plan accordingly in advance. Since this is not happening in WordPress not even happen, we need to tap a little more - or in the case of the archive dropdown even much more:

<form id="archivform" action="<?php bloginfo('url'); ?>" method="get">
    <label for="archivselect">skip to month</label>
    <select id="archivselect" name="m">
        <option value="">-- Please select</option>
        <?php
            $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, COUNT(ID) as `posts`
                FROM $wpdb->posts
                WHERE post_type = 'post' AND post_status = 'publish'
                GROUP BY YEAR(post_date), MONTH(post_date)
                ORDER BY post_date DESC";
            $key = md5($query);
            $cache = wp_cache_get('select_archives', 'general');
            if(!isset($cache[$key])){
                $arcresults = $wpdb->get_results($query);
                $cache[$key] = $arcresults;
                wp_cache_set('select_archives', $cache, 'general');
            }
            else{
                $arcresults = $cache[$key];
            }
            if($arcresults){
                global $wp_locale;
                foreach((array) $arcresults as $arcresult){
                    $value = $arcresult->year.$arcresult->month;
                    $text = sprintf(__('%1$s %2$d'), $wp_locale->get_month($arcresult->month), $arcresult->year);
                    $count = ' ('.$arcresult->posts.')';
                    $selected = (is_month() && get_query_var('year').get_query_var('monthnum') == $value) ? 'selected' : '';
                    echo '<option '.$selected.' value="'.$value.'">'.$text.$count.'</option>';
                }
            }
        ?>
    </select>
    <input id="archivbutton" value="Archiv abrufen" type="submit">
</form>

The problem with the Archive, is that without a custom SQL query, you cannot get to the information, which you need for a monthly archive. So there is no other way then to manually enter the database and cache the result manually. The principle is identical: simply output a conventional form and then six small lines of JavaScript:

<script type="text/javascript">
    document.getElementById('archivselect').onchange = function(){
        if(this.value){
            document.getElementById('archivform').submit();
        }
    };
    document.getElementById('archivbutton').style.display = 'none';
</script>

To summarize: many lines of code, but the principle is not complicated. Unobtrusive JavaScript is a question of intelligent planning and if it is not included as with WordPress automatically, you have to do it. With traditional websites, there is no reason to operate completely dependent on JavaScript, and should there be more effort, it is worth the clean separation of the layers and the accessibility bonus.

Guest Post

This post was written by Peter Kröner peterkroener.de.

Peter Kröner is freelance web designer and developer and also author of the HTML5-book.
On peterkroener.de he blogs on all kind of topics in web technology.

Thank you very much from our part to Peter.

If you also like to have your interesting post published on our website, please let us know on our contact page. Of course we will appreciate your contribution!

Comments are closed.

2 comments

  1. Alex

    Sorry, but may be "Unobtrusive JavaScript"

  2. Dario Ferrer

    If exists an 'onchange' function, the submit button is unneeded when js is enabled. You can enclose it between noscript tags: