<h1>Hover over the links</h1>
<nav class="mynav">
<ul>
<li><a href="">Home</a></li>
<li><a href="">About</a></li>
<li><a href="">Company</a></li>
<li><a href="">Work</a></li>
<li><a href="">Clients</a></li>
<li><a href="">Contact</a></li>
</ul>
</nav>
<span class="target"></span>
body {
background: #ededed;
padding: 0 20px;
margin: 0;
font-family: 'Open Sans', Arial, sans-serif;
}
h1 {
text-align: center;
margin: 80px 0;
}
.mynav ul {
display: flex;
justify-content: center;
flex-wrap: wrap;
list-style-type: none;
padding: 0;
}
.mynav li:not(:last-child) {
margin-right: 20px;
}
.mynav a {
display: block;
font-size: 20px;
color: black;
text-decoration: none;
padding: 7px 15px;
}
.target {
position: absolute;
border-bottom: 4px solid transparent;
z-index: -1;
transform: translateX(-60px);
}
.mynav a,
.target {
transition: all .35s ease-in-out;
}
(function() {
const target = document.querySelector(".target");
const links = document.querySelectorAll(".mynav a");
const colors = ["deepskyblue", "orange", "firebrick", "gold", "magenta", "black", "darkblue"];
function mouseenterFunc() {
if (!this.parentNode.classList.contains("active")) {
for (let i = 0; i < links.length; i++) {
if (links[i].parentNode.classList.contains("active")) {
links[i].parentNode.classList.remove("active");
}
links[i].style.opacity = "0.25";
}
this.parentNode.classList.add("active");
this.style.opacity = "1";
const width = this.getBoundingClientRect().width;
const height = this.getBoundingClientRect().height;
const left = this.getBoundingClientRect().left + window.pageXOffset;
const top = this.getBoundingClientRect().top + window.pageYOffset;
const color = colors[Math.floor(Math.random() * colors.length)];
target.style.width = `${width}px`;
target.style.height = `${height}px`;
target.style.left = `${left}px`;
target.style.top = `${top}px`;
target.style.borderColor = color;
target.style.transform = "none";
}
}
for (let i = 0; i < links.length; i++) {
links[i].addEventListener("click", (e) => e.preventDefault());
links[i].addEventListener("mouseenter", mouseenterFunc);
}
function resizeFunc() {
const active = document.querySelector(".mynav li.active");
if (active) {
const left = active.getBoundingClientRect().left + window.pageXOffset;
const top = active.getBoundingClientRect().top + window.pageYOffset;
target.style.left = `${left}px`;
target.style.top = `${top}px`;
}
}
window.addEventListener("resize", resizeFunc);
})();
View Compiled
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.