I have two links namely "Total Users" and "Users Information". By default "Total Users" is underlined but when I click on "Users Information" the underline moves to that clicked link and then comes back to its default position ie "Total Users". Can someone please help me with this, I want to underline to stay on the link that I've clicked
My HTML code:
<nav>
<a style="margin-left: 140px;"
routerLink="totalUsers"
routerLinkActive="active" id="uno" class="one">
Total Users
</a>
<a routerLink="usersInformation"
routerLinkActive="active" id="dos" class="two">
Users Information
</a>
<hr/>
</nav>
My CSS code:
a {
display: inline-block;
width: 11%;
text-decoration: none;
color: #333;
}
#uno:focus ~ hr {
margin-left: 140px;
}
#dos:focus ~ hr {
margin-left: 22.1% !important;
width: 10.3% !important;
}
hr {
height: 0.2rem;
width: 6.5%;
margin-left: 140px ;
margin-top: 0;
background: #d9534f;
border: none;
transition: 0.3s ease-in-out;
}
I did something like this and it worked. Played around with margin-left, initiating margin-left with 0 and then moving it 100px on clicking second link and back to 0 on clicking the first link. codesandbox
hr {
height: 0.2rem;
width: 6.5%;
margin-left: 0;
margin-top: 0;
background: #d9534f;
border: none;
transition: 0.3s ease-in-out;
}
#two:focus ~ hr {
margin-left: 100px;
}
#one:focus ~ hr {
margin-left: 0px;
}
I would suggest you to use background-image: linear-gradient() instead of using hr tag which is much easier and you could add/remove class to switch the underline.
let one = document.querySelector('.one span');
let two = document.querySelector('.two span')
one.addEventListener('click',function(){
one.classList.add('effect');
two.classList.remove('effect')
});
two.addEventListener('click',function(){
one.classList.remove('effect');
two.classList.add('effect')
});
span {
width: 11%;
text-decoration: none;
color: #333;
display: inline-block;
cursor:pointer;
}
.effect{
background-image: linear-gradient( #d9534f, #d9534f);
background-repeat: no-repeat;
background-position: bottom left;
background-size: 50% 4px;
}
<nav>
<a style="margin-left: 140px;" routerLink="totalUsers" routerLinkActive="active" id="uno" class="one">
<span class='effect'> Total Users</span>
</a>
<a routerLink="usersInformation" routerLinkActive="active" id="dos" class="two"><span>
Users Information
</span> </a>
</nav>