Create ‘option’ elements from ‘a’ elements
On 1301px or larger viewports you’ll see the ul > li > a elements.
On 1300px ot smaller viewports you’ll see the select element.
The JS code will take any elements from the ul > li > a elements and create them as option elements.
There is also JavaScript code that allows the user to jump to the particular anchor using the select element.
JavaScript
// convert .jumpnav links to select option elements
const jumpNav = () => {
const jumpNavLink = document.querySelectorAll('.jump-nav ul li a')
const jumpNavSelect = document.querySelector('.jump-nav select')
const pageNameSearch = window.location.pathname + window.location.search
if (jumpNavSelect) {
jumpNavLink.forEach((element) => {
let elementHref = element.getAttribute('href')
let elementInnerHtml = element.innerHTML
let newOption = document.createElement('option')
newOption.setAttribute('value', elementHref)
newOption.innerHTML = elementInnerHtml
jumpNavSelect.appendChild(newOption)
})
jumpNavSelect.addEventListener('change', () => {
let jumpNavValue = jumpNavSelect.options[jumpNavSelect.selectedIndex].value
if (jumpNavValue !== 'Jump to a Section' && jumpNavValue !== pageNameSearch) {
window.open(jumpNavValue, '_self')
}
})
}
}
jumpNav()
HTML
<nav class="jump-nav">
<ul>
<li><a href="#anchor-1">Anchor 1</a></li>
<li><a href="#anchor-2">Anchor 2</a></li>
<li><a href="#anchor-3">Anchor 4</a></li>
<li><a href="#anchor-4">Anchor 5</a></li>
<li><a href="#anchor-5">Anchor 5</a></li>
<li><a href="#anchor-6">Anchor 6</a></li>
<li><a href="#anchor-7">Anchor 7</a></li>
</ul>
<select>
<option>Jump to a Section</option>
</select>
</nav>
CSS
.jump-nav {
padding-inline: 1em;
ul {
display: flex;
justify-content: space-between;
align-items: center;
gap: 1em;
margin: 0;
padding: 0;
list-style: none;
@media (max-width: 1300px) {
display: none;
}
}
li {
flex-grow: 1;
flex-shrink: 0;
flex-basis: auto;
display: flex;
}
a {
flex-grow: 1;
flex-shrink: 0;
flex-basis: auto;
text-align: center;
padding-block: 1em;
background-color: #D19F60;
border: 2px solid #D19F60;
color: #fff;
font-size: 1.2rem;
line-height: 1;
text-decoration: none;
text-transform: uppercase;
&:hover,
&:focus {
background-color: #fff;
color: #D19F60;
}
}
select {
display: none;
margin-inline: auto;
height: 46px;
padding-left: 0.5em;
box-shadow: inset 1px 1px 3px rgb(0 0 0 / 50%);
border: 1px solid #c4c4c4;
border-radius: 5px;
color: #000;
@media (max-width: 1300px) {
display: block;
}
}
}