Uikit Switcher Component & Current Window Hash

Uikit Switcher Component & Current Window Hash

Uikit have Switcher component - .

I need the selected tab added to the address bar and not reset when the page reloads. for example

<ul class="uk-subnav uk-subnav-pill" uk-switcher>
<li><a href="#tab1">Item</a></li>
<li><a href="#tab2">Item</a></li>
<li><a href="#tab3">Item</a></li>
<ul class="uk-switcher uk-margin">
<li>Hello!</li>
<li>Hello again!</li>
<li>Bazinga!</li>

Please help with the solution of this problem. Thanks!

1 Answer

Add this piece of code before closing body tag. This is one idea, you may develop on this

// Replace .uk-subnav with your switcher element
const switcherEl = document.querySelector('.uk-subnav');
const anchors = switcherEl.querySelectorAll('li > a');
const switcher = UIkit.switcher(switcherEl);

// Show content corresponds to location hash
let active = 0;
while(anchors[active]) {  
  if(anchors[active].hash === window.location.hash) {
    switcher.show(active);    
    break;
  }
  active++;
}

// Update location hash in address bar.
switcherEl.addEventListener('click', (event) => window.location.hash = event.target.hash.substr(1));
1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Sophia Al-Mansoor
Author

Sophia Al-Mansoor

Sophia analyzes international trade, startup ecosystems, retail transformation, and supply chain logistics for modern digital publications.