I have created a side navigation bar and I am using it on two html pages using jquery. There is also an underline in the navigation bar which moves depending on the selected nav link. Below is the code for nav bar and html pages:
sidenav.html
<script type="text/javascript" src="script.js"></script>
<link href="design.css" rel="stylesheet" type="text/css" />
page1.html
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$("#nav-placeholder").load("sidenav.html");
});
</script>
<div id="nav-placeholder">
</div>
page1!
page2.html
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(function(){
$("#nav-placeholder").load("sidenav.html");
});
</script>
<div id="nav-placeholder">
</div>
page2!
script.js: Script for movement of underline:
function ul(index) {
console.log('click!' + index)
var underlines = document.querySelectorAll(".underline");
for (var i = 0; i < underlines.length; i++) {
console.log(index*100)
underlines[i].style.transform = 'translate3d(0, ' + index * 70 + 'px, 0)';
}
}
Now what is happening is, underline was supposed to move down when switching to nav links using nav bar. But the issue is, as I go from page1.html to page2.html, screen refreshes and underline comes to its original position.
What my ask is, how to achieve this underline movement while switching between html pages.
I am not sure if my approach is right as I am new to UI. Please provide some references on how to switch between pages using nav bar and highlight selected nav.
Thank you.
You can change style on page load. You can get the page filename. I have assumed your sidebar.html content.
<div class="container">
<div id="nav-placeholder">
<nav>
<ul>
<li class="nav_link underline"><a href='page1.html'>Page 1</a></li>
<li class="nav_link underline"><a href='page2.html'>Page 2</a></li>
</ul>
</nav>
</div>
</div>
<script>
$(document).ready(function() {
// $("#nav-placeholder").load("sidenav.html");
var filename = location.pathname.substr(location.pathname.lastIndexOf("/")+1);
console.log(filename);
var underlines = document.querySelectorAll(".underline");
for (var i = 0; i < underlines.length; i++) {
console.log(underlines[i].querySelector('a').getAttribute('href'));
if(filename == underlines[i].querySelector('a').getAttribute('href') ) {
console.log('Yeah!!!');
underlines[i].style.transform = 'translate3d(0, ' + i * 70 + 'px, 0)';
}
}
});
</script>