Code a Mobile-Friendly Menu in WordPress

One of the most common used method to display a menu on mobile screens is by using the toggle effect.

This method requires you to add custom code to your WordPress files. If you haven’t done this before, then take a look at our guide on pasting snippets from web in WordPress.

First you need to open a text editor like notepad and paste this code.

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
27
28
29
30
31
32
( function() {
    var nav = document.getElementById( 'site-navigation' ), button, menu;
    if ( ! nav ) {
        return;
    }
    button = nav.getElementsByTagName( 'button' )[0];
    menu   = nav.getElementsByTagName( 'ul' )[0];
    if ( ! button ) {
        return;
    }
    // Hide button if menu is missing or empty.
    if ( ! menu || ! menu.childNodes.length ) {
        button.style.display = 'none';
        return;
    }
    button.onclick = function() {
        if ( -1 === menu.className.indexOf( 'nav-menu' ) ) {
            menu.className = 'nav-menu';
        }
        if ( -1 !== button.className.indexOf( 'toggled-on' ) ) {
            button.className = button.className.replace( ' toggled-on', '' );
            menu.className = menu.className.replace( ' toggled-on', '' );
        } else {
            button.className += ' toggled-on';
            menu.className += ' toggled-on';
        }
    };
} )(jQuery);

Now you need to save this file as navigation.js on your desktop.

Next, you need to open a FTP client to upload this file to /wp-content/themes/your-theme-dir/js/ folder on your WordPress site.

Replace your-theme-directory with your current theme’s directory. If your theme directory does not have a js folder, then you need to create it.

After uploading the JavaScript file, the next step is to make sure your WordPress site loads this JavaScript. You will need to add the following code to your theme’s functions.php file.

1
wp_enqueue_script( 'wpb_togglemenu', get_template_directory_uri() . '/js/navigation.js', array('jquery'), '20160909', true );

Now we need to add the navigation menu into our WordPress theme. Usually navigation menu is added into a theme’s header.php file.

1
2
3
4
<nav id="site-navigation" class="main-navigation" role="navigation">
            <button class="menu-toggle">Menu</button>
            <?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?>
</nav>

We are assuming that the theme location defined by your theme is called primary. If it is not, then use the theme location defined by your WordPress theme.

The final step is to add CSS so that our menu uses the right CSS classes for toggle to work when viewed on mobile devices.

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
/* Navigation Menu */
.main-navigation {
    margin-top: 24px;
    margin-top: 1.714285714rem;
    text-align: center;
}
.main-navigation li {
    margin-top: 24px;
    margin-top: 1.714285714rem;
    font-size: 12px;
    font-size: 0.857142857rem;
    line-height: 1.42857143;
}
.main-navigation a {
    color: #5e5e5e;
}
.main-navigation a:hover,
.main-navigation a:focus {
    color: #21759b;
}
.main-navigation ul.nav-menu,
.main-navigation div.nav-menu > ul {
    display: none;
}
.main-navigation ul.nav-menu.toggled-on,
.menu-toggle {
    display: inline-block;
}
// CSS to use on mobile devices
@media screen and (min-width: 600px) {
.main-navigation ul.nav-menu,
    .main-navigation div.nav-menu > ul {
        border-bottom: 1px solid #ededed;
        border-top: 1px solid #ededed;
        display: inline-block !important;
        text-align: left;
        width: 100%;
    }
    .main-navigation ul {
        margin: 0;
        text-indent: 0;
    }
    .main-navigation li a,
    .main-navigation li {
        display: inline-block;
        text-decoration: none;
    }
    .main-navigation li a {
        border-bottom: 0;
        color: #6a6a6a;
        line-height: 3.692307692;
        text-transform: uppercase;
        white-space: nowrap;
    }
    .main-navigation li a:hover,
    .main-navigation li a:focus {
        color: #000;
    }
    .main-navigation li {
        margin: 0 40px 0 0;
        margin: 0 2.857142857rem 0 0;
        position: relative;
    }
    .main-navigation li ul {
        margin: 0;
        padding: 0;
        position: absolute;
        top: 100%;
        z-index: 1;
        height: 1px;
        width: 1px;
        overflow: hidden;
        clip: rect(1px, 1px, 1px, 1px);
    }
    .main-navigation li ul ul {
        top: 0;
        left: 100%;
    }
    .main-navigation ul li:hover > ul,
    .main-navigation ul li:focus > ul,
    .main-navigation .focus > ul {
        border-left: 0;
        clip: inherit;
        overflow: inherit;
        height: inherit;
        width: inherit;
    }
    .main-navigation li ul li a {
        background: #efefef;
        border-bottom: 1px solid #ededed;
        display: block;
        font-size: 11px;
        font-size: 0.785714286rem;
        line-height: 2.181818182;
        padding: 8px 10px;
        padding: 0.571428571rem 0.714285714rem;
        width: 180px;
        width: 12.85714286rem;
        white-space: normal;
    }
    .main-navigation li ul li a:hover,
    .main-navigation li ul li a:focus {
        background: #e3e3e3;
        color: #444;
    }
    .main-navigation .current-menu-item > a,
    .main-navigation .current-menu-ancestor > a,
    .main-navigation .current_page_item > a,
    .main-navigation .current_page_ancestor > a {
        color: #636363;
        font-weight: bold;
    }
    .menu-toggle {
        display: none;
    }
    
    }

You can now visit your website and resize your browser screen to see your responsive toggle menu in action.

Toggle menu preview

Troubleshooting: Depending on your WordPress theme you may need to adjust the CSS. Use inspect element tool to figure out the CSS conflicts with your theme.

Method 4: Add a Slide-In Mobile Menu in WordPress

Another common technique to add a mobile menu is by using a slide-in panel menu (as shown in Method 1).

Method 4 requires you to add code to your WordPress theme files, and it is just a different way of accomplishing the same results as Method 1.

First, you need to open a plain text editor like Notepad and add the following code to a blank text file.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
(function($) {
$('#toggle').toggle(
    function() {
        $('#popout').animate({ left: 0 }, 'slow', function() {
            $('#toggle').html('<img src="http://www.example.com/wp-content/themes/your-theme/images/menu.png" alt="close" />');
        });
    },
    function() {
        $('#popout').animate({ left: -250 }, 'slow', function() {
            $('#toggle').html('<img src="http://www.example.com/wp-content/themes/your-theme/images/menu.png" alt="close" />');
        });
    }
);
})(jQuery);

Don’t forget to replace example.com with your own domain name and your-theme with your actual theme directory. Save this file as slidepanel.js to your desktop.

Now you will need an image which will be used as a menu icon. A hamburger icon is most commonly used as the menu icon. You will find tons of such images from different websites. We will be using the menu icon from Google Material Icons library.

Once you find an image that you want to use, save it as menu.png.

Next, you need to open a FTP client client and upload slidepanel.js file to /wp-content/your-theme/js/ folder.

If your theme directory does not have the JS folder, then you need to create tit and then upload your file.

After that, you need to upload menu.png file to /wp-content/themes/your-theme/images/ folder.

Once the files are uploaded, we need to make sure that your theme loads the JavaScript file you just added. We will achieve this by enqueuing the JavaScript file.

Add this code to your theme’s functions.php file.

1
wp_enqueue_script( 'wpb_slidepanel', get_template_directory_uri() . '/js/slidepanel.js', array('jquery'), '20160909', true );

Now we need to add the actual code in your theme’s header.php file to display the navigation menu. You should look for code similar to this:

1
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?>

You want to wrap existing navigation menu with the HTML code to display your slide panel menu on smaller screens.

1
2
3
4
5
<div id="toggle">
<img src="http://www.example.com/wp-content/themes/your-theme/images/menu.png" alt="Show" /></div>
<div id="popout">
<?php wp_nav_menu( array( 'theme_location' => 'primary', 'menu_class' => 'nav-menu' ) ); ?>
</div>

Notice that your theme’s navigation menu is still there. We have just wrapped it around HTML that we need to trigger slidepanel menu.

Last step is to add CSS to hide the menu image icon on larger screens. You will also need to adjust the position of the menu icon.

Here is a sample CSS that you can use as an starting point:

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
@media screen and (min-width: 769px) {
#toggle {
display:none;
}
}
@media screen and (max-width: 768px) {
#popout {
position: fixed;
height: 100%;
width: 250px;
background: rgb(25, 25, 25);
background: rgba(25, 25, 25, .9);
color: white;
top: 0px;
left: -250px;
overflow:auto;
}
#toggle {
float: right;
position: fixed;
top: 60px;
right: 45px;
width: 28px;
height: 24px;
}
.nav-menu li {
border-bottom:1px solid #eee;
padding:20px;
width:100%;
}
.nav-menu li:hover {
background:#CCC;
}
.nav-menu li a {
color:#FFF;
text-decoration:none;
width:100%;
}
}

Depending on your WordPress theme, you may need to adjust the CSS to avoid conflicts.

Laws of UX

Remember when your mother warned you not to run down the stairs because you could fall and hurt yourself? Or when you held your palm over a candle’s flame and started feeling the burn? The “laws of UX” are similar — they are cause and effect relationships where one event (the cause) makes another event happen (the effect). Whether a designer acknowledges them or not, the “laws” rule and operate — and will affect the effectiveness of a design.

Take Miller’s Law, for example, which states that “the average person can only keep around seven items in their working memory.” When the rule is disregarded, people are forced to think more than they should have to. UX professionals refer to this phenomenon as cognitive overload.

Ignoring Miller’s Law can have negative consequences that may impede the UX, i.e., if there are too many things people have to remember, it could cause frustration and decision paralysis.

Presenting too many choices in a hard-to-comprehend format may overload the user’s cognitive capacity, causing frustration and decision paralysis. (Source: UI Patterns)

A cousin to Miller’s Law is Hick’s Law, which states: “The time it takes to make a decision increases with the number and complexity of choices.” It’s easy to see how they’re related. In a poorly designed scenario, both of these laws could be violated at the same time by a UI that presents too many choices andasks people to remember too many things when trying to complete a task.

Then there’s Fitts’ Law. Specific to human-computer-interaction (HCI) on desktops, Fitts’ Law predicts that “the time required to rapidly move to a target area is a function of the ratio between the distance to the target and the width of the target” — for example, how large a button is, and how far it is from the cursor’s position in the UI.

Many UX designers forget that Fitts’ Law — as well as many other UX laws — can also be used creatively by placing destructive features in a UI in a difficult-to-reach position — such as a reset form or the “cancel” button on a web form.

It’s important to remember that, typically, Fitts’ Law doesn’t apply to mobile. However, even though there is no cursor to travel to a target location, a designer can use the distance from one tap to another to either impede or assist an interaction. For example, a “logout” icon can be placed at the top of the mobile screen, and the confirmation could come up on the bottom.

A great customer experience is based on trust and meaningful, consistent interactions. Any designer worth their salt must consider cognitive psychology and the effect of their work on their intended audience. For example, if one considers a bank with over 25 million mobile customers it can be easily seen how ignoring the laws of UX could seriously hinder their app’s UX, and consequently affect their bottom line.

Taken collectively, observing these laws of UX can help guide a digital designer toward creating the most effective design for any given product.

Even though they are not actual laws, but rather tried and true cause and effect relationships, UX designers should nevertheless, take notice of the driving forces behind the laws of UX in order to design superior products.

Here Are Some of These UX Laws

(more in the infographic below)

Fitts’ Law demonstrates how to ease interactions through the careful sizing and positioning of interface elements. It states: The time it takes to acquire a target is a function of the distance to and size of the target. It is particularly important when designing buttons and other clickable on-screen elements.

Hick’s Law, or the Hick–Hyman law, named after British and American psychologists William Edmund Hick and Ray Hyman, describes the time it takes for a person to make a decision as a result of the possible choices he or she has: Increasing the number of choices will increase the decision time logarithmically.

Miller’s Law states that the average person can only keep 7 (+ or — 2) items in their working memory. It emphasizes the benefits of “chunking” to ease complex tasks by grouping information related by perceptual features such as types of fruit or parts of speech.

Occam’s Razor refers to the philosophical idea or scientific principle that if two explanations exist for an occurrence, the simpler one is usually the better choice — e.g., one of the fence posts is broken. Either a) a moose ran through it or b) Some screws fell out because it is old. “B” is more likely.

William of Ockham, a Franciscan friar who studied logic in the 14th century, first made this principle, that states, “More things should not be used than are necessary,” well known. The word “razor” is a metaphor —Occam’s Razor gets rid of unnecessary explanations just like a razor shaves off the extra hair.

The Pareto Principle (also known as the 80/20 rule, the law of the vital few, or the principle of factor sparsity) states that, for many events, roughly 80% of the effects come from 20% of the causes.

The Isolation Effect (also known as the Von Restorff Effect) is the tendency to recall something that stands out in a group and afford it more weighting than its peers. It is named after German psychologist Hedwig Von Restorff, who first documented it in 1933.

German psychologist Hermann Ebbinghaus is credited with creating the term “serial position effect.” The serial position effect is the tendency of a person to recall the first and last items in a series best and the middle items worst.

Javascript Objects

Objects

Definition: Objects in Javascript are used to group related data and functions together. Each piece of data inside an object is called a property.

Syntax:

var myComputer = { // variable is assigned to object starts with a curly brace
operatingSystem: 'Mac', // each property starts with a property name, semicolon, property value in quotes if string. Each property is separated by a comma

screenSize: '15 inches',
purchaseYear: '2011'
}; // ends with a curly brace. The last object ends with a semicolon

Calling an Object

To call an entire object, type object name.
To call a property, type the object name followed by a period and property name.

Method

A method is a property of an object that is a function.

For Loop

Example in English: i = 0 // Initialization Say “hey” if i < 3 // Condition Increase i by 1 // Final Expression Syntax: for (initializtion; condition; final-expression) { } Example: for (var i = 0; i < 3; i++) { console.log("hey"); }

Javascript Functions

Functions

Definition: Functions are just recipes. To use declare function followed by function name and parenthesis and braces. Lines within a function ends in semicolons.
Syntax:// function syntax – runs code with no options
function functionName() {
// code here
}

Functions with Parameters

Parameter – Values inside the () when creating a function are called parameters.
Arguments – Values inside the () when running a function are called arguments.

Syntax:// function syntax – runs code with parameter with argument
function functionName(parameter) {
// code here
}
// run function
functionName(argument)

Customizing Functions

A variable or ‘string’ can be added to a function inside the (). This makes a function customizable.

Example:
function sayHiTo(person) {
console.log(‘hi’, person);
}

//run function
sayHiTo(‘gordon’) // person = ‘gordon’

= hi gordon

Functions Inside Functions

var todos = [‘item 1’, ‘item 2’, ‘item 3’]

function displayTodos() {
console.log(todos);
}

function addTodo(todo) {
todos.push(todo);
displayTodos();
}

Functions with Multiple Parameters

Example:
function changeTodo(position, newValue) {
todos[position] = newValue;
displayTodos();
}

Javascript Comments

Create a comment by writing // at the beginning of the line

Complete code for Todo List
var todos = [‘item 1’, ‘item 2’, ‘item 3’];

// It should have a function to display todos
function displayTodods () {
console.log(‘My Todos:’, todos);
}

//It should have a function to add todos
function addTodo(todo) {
todos.push(todo);
displayTodos();
}

//It should have a function to change todos
function changeTodo(position, newValue) {
todos[position] = newValue;
displayTodos();
}

//It should have a function to delete todos
function deleteTodo(position) {
todos.splice(position, 1);
displayTodos();
}

Variable Scope in Functions

If you’re inside a function, you can look out and see data, but the opposite isn’t true. If you’re outside, you can’t look in

Example

var myName = ‘Gordon’;

function sayName() {
var secret = ‘watchandcode’;
console.log(myName)
}
sayName(); // ‘Gordon’
console.log(secret); // error – can’t see variable inside function

Checking Your Code with Circles & Arrows

Draw circles around each function. Draw arrows from where the variable is being called to where it is declared. The only rule is arrows can’t enter circles, only exit. Any arrow trying to enter a circle is trying to read variable data that is out of its scope.

Javascript Arrays

Arrays

Definition: Array is a term for a list in JavaScript
Syntax: Each item surrounded by a quotation and group surrounded by bracket separated with commas.
Example: [‘Item 1’, ‘Item 2’, ‘Item 3’]

Variables

Definition: Variables is a container that stores information
Syntax: start with var, then variable name, =, then the value to set variable to
Example: var todos = ['Item 1', 'Item 2', 'Item 3']

console.log() Function

console.log() – Prints to console. Can take multiple items.
Example:

var todos = ['Item 1', 'Item 2', 'Item 3']
console.log("My ToDos:", todos)
= My ToDos: ["item 1", "item 2", "item 3"]

Adding Array Items

.push() Function

.push() – command to add items to an array. Think of it as pushing to (adding to the end of) the array. Returns new number of items in the array
Example: todos.push(‘item 4’)
= 4
console.log(“My ToDos:”, todos)
= My ToDos [“item 1”, “item 2”, “item 3” ‘item 4’]

Calling Array Items

Call a array item – to call a specific item in an array use brackets with a number within. Important, the first item is 0, second item is 1, ect.
Syntax: varName[number]
Example:
todos[0]
= item 1

Changing Array Items

Change an array item – to change an array i
Syntax: varName[number] = ‘new value’
Example: todos[0] = ‘item 1 updated’
= “item 1 updated”

Deleting Array Items

.splice() – Deletes array items. requires first item to delete and how many items. Returns the deleted item. If [] is returned, the command wasnt able to delete anything.

Syntax: array.splice(firstItem, numItems)
Example:
todos.splice(0, 1) – deletes first item