I started creating my own travel WordPress theme in the last quarter of 2016. More about the idea and all of the functionality in another post – coming soon. Basically, I am web developing this custom WordPress theme to set up on the fly for different travel adventures / tours / destinations I do. This serve as a travel blog for that particular trip. Eg. capetowntovicfalls.me, vietnam-cambodia.me, travellingturkey.me.
The way I’ve decided to design the main navigation, is to open up as full screen and display the list of all the days / places of the specific trip. By default, styled in the CSS, the whole list is centred vertically in the full screen. Each list item has a padding, top and bottom of 2.4%.
Although, as it goes, no trip is going to be the same. Some will be longer than others. Which means the spacing of the list need to adjust dynamically, without me having to adjust the style for each trip/website. Sometimes I might not even know how many days I will be travelling… 🙂
Using Vanilla JavaScript
Up to 10 items in the navigation list fit nicely across all devices, using the default CSS. When the list gets longer than that, the margins between each row of the list need to be calculated dynamically to ensure the list always fit within the full screen. I am using JavaScript to do just that. Here is my plan…
1. Count the items in the navigation list
First I need to find out how many items are in the list and store the result in a variable. If it is 10 or less, the default CSS styles stay the same. If there are more than 10 items, I need to know how many and overwrite the default CSS styles accordingly.
var listitems = document.querySelectorAll('.primary-menu .menu-item').length;
2. Dynamically evenly space the list vertically
Adding more to the calculation, when there are more than 10 items, the list container ul
has to be set at 100% in height. Then using the number of list items, to be divided in the 100%. The result of that need to set the height of each list item:
var listitems = document.querySelectorAll('.primary-menu .menu-item');
//change the spacing of the list when there are more than 10 items
if (listitems.length > 10) {
var primarymenuUl = document.querySelector('.primary-menu ul');
primarymenuUl.style.height = '100%';
var listItemHeight = (100 / listitems.length) + '%' ;
//loop through the list items and set the height of each
for (var i = 0; i < listitems.length; i++) {
listitems[i].style.height = listItemHeight;
}
}
The jQuery version
If the jQuery library is already loaded in the site, then the following can also be used:
jQuery(document).ready(function($) {
var listitems = $('.primary-menu .menu-item').length;
if (listitems > 10) {
$('.primary-menu ul').height('100%');
var listitemHeight = 100 / listitems;
$('.primary-menu .menu-item').height(listitemHeight + '%');
}
});
Leave a Reply