How to minimize WP dashboard menu programmatically?

Add a javascript to all admin pages:

add_action( 'admin_print_scripts', 'auto_collapse_menu' );

function auto_collapse_menu(){

    wp_enqueue_script( 'autocollapsemenu', plugins_url( 'autocollapsemenu.js', __FILE__ ), array( 'jquery' ), false, true );

}

The javascript:

jQuery(document).ready( function($){

    // catch every click inside element with ID 'adminmenu'
    $( '#adminmenu' ).click(
        function(e){

            // true if the menu is folded, false if not
            var bodyFolded    = $(document.body).hasClass( 'folded' );

            // true if the uncollapse button was clicked, else false 
            var uncollapseBtn = $(e.target).is( 'div' );

            // true if the clicked element has a class
            var hasClass      = ( typeof $(e.target).attr( 'class' ) ) != 'undefined';

            if ( ! bodyFolded && ! uncollapseBtn && hasClass ) {
                body.addClass( 'folded' );
                setUserSetting( 'mfold', 'f' );
            }
        }
    );

});

We want to catch all clicks inside the admin menu. If we catch a click inside the admin menu, we have to check if the admin menu is already folded. Now we have to check if the unfold button (uncollapse button) was clicked. This is a bit tricky, because if the admin menu is folded, the unfold button has no class or id. It is simply a <div>-element. But all others menu items are also <div>-elements. So we can test if the clicked element has a class. If the clicked element has a class, it was not the unfold button and the menu should be folded.

Now put all together: If the admin menu is not folded AND the clicked element is not a div element AND the clicked element has a class, then we expect it was not the unfold button that was clicked and the menu should be folded.

In this case we add the class folded to teh body element. Now we have to store that we have folded the admin menu. Because on the next page load the added class will be removed. We do this with setUserSetting( 'mfold', 'f' ).

setUserSetting() is a function from wp-includes/js/utils.js and store a value in the WordPress cookie.