Elements

Mousemove button

05 Apr 2023

Button with ui item that follow mouse cursor
HTML
SCSS
PostCSS
JS
                            <a href="#" class="btn">
    <span class="circle"></span>
    <span>View all our news & insights</span>
</a>
                        
                            .btn {
  position: relative;
  min-height: 53px;
  display: flex;
  align-items: center;
  color: #102E5BFF;
  padding-left: 14px;
  width: fit-content;

  span {
    position: relative;
    z-index: 5;
    pointer-events: none;
  }

  .circle {
    content: "";
    width: 53px;
    height: 53px;
    border: 1px solid var(--blue-light);
    border-radius: 50%;
    position: absolute;
    z-index: 1;
    transition: all 0.2s ease;
    top: 0;
    left: 0;
  }

  @include media(1025) {
    &:hover {
      .circle {
        transform: scale(0.5);
      }
    }
  }
}
                        
                            .btn {
	position: relative;
	min-height: 53px;
	display: flex;
	align-items: center;
	color: #102E5BFF;
	padding-left: 14px;
	width: fit-content;

	span {
		position: relative;
		z-index: 5;
		pointer-events: none;
	}

	.circle {
		content: "";
		size: 53px;
		border: 1px solid var(--blue-light);
		border-radius: 50%;
		position: absolute;
		z-index: 1;
		transition: all 0.2s ease;
		top: 0;
		left: 0;
	}

	@mixin media 1025 {
		&:hover {
			.circle {
				transform: scale(0.5);
			}
		}
	}
}
                        
                            function followOnHover(hovered, following) {
	const onMouseMove = (event) => {
		let x = event.offsetX;
		let y = event.offsetY;

		if (event.target.classList.contains("btn")) {
			following.style.transform = `translate(calc(${x}px - 50%), calc(${y}px - 50%)) scale(0.5)`;
			following.style.borderWidth = "4px";
		}
	};

	const removeMouseMove = () => {
		following.style.transform = `translate(0, 0) scale(1)`;
		following.style.borderWidth = "";
	};

	hovered.addEventListener("mousemove", onMouseMove);

	hovered.addEventListener("mouseleave", removeMouseMove);

	if (window.innerWidth < 1025) {
		hovered.removeEventListener("mousemove", onMouseMove);
		hovered.removeEventListener("mouseleave", removeMouseMove);
	}
}

const btn = document.querySelector(".btn");
const circle = btn.querySelector(".circle");

followOnHover(btn, circle);
                        
0