crosshair cursor

by James Connolly

HTML

<body>
<p>
Lorem ipsum dolor sit amet. <a href="#">Learn More</a>
</p>
<div class="cursor">
  <div class="circle"></div>
  <div class="dot"></div>
  <div class="crosshair"></div>
  <div class="crosshair"></div>
</div>
</body>

SCSS

body {
  cursor: none;
}

a {
	cursor: none;
}

.cursor {
	position: absolute;
	pointer-events: none;
  opacity: 0.6;

// globals
.circle, .dot, .crosshair, .crosshair::before, .crosshair::after {
	transition: all 0.2s ease-out;
	border-radius: 999px;
}

.circle, .crosshair {
	width: 75px;
	height: 75px;
	position: absolute;
	top: 50%;
	left: 50%;
	transform: translate(-50%, -50%);
}

.circle, .dot {
	border-radius: 50%;
}

// circle
.circle {
	border: 3px solid red;
}

// dot
.dot {
	width: 12px;
	height: 12px;
	background: red;
}

// crosshair
.crosshair {

	&:before, &:after {
		content: '';
		background: red;
		position: absolute;
	}

	&:nth-child(odd) {
		&:before, &:after {
			width: 0;
			height: 3px;
			top: calc(50% - 1px);
		}

		&:before {
			left: -8px
		}

		&:after {
			right: -8px
		}
	}

	&:nth-child(even) {
		&:before, &:after {
			width: 3px;
			height: 0;
			left: calc(50% - 1px);
		}

		&:before {
			top: -8px
		}

		&:after {
			bottom: -8px
		}
	}
}

&.bullseye {

	.circle, .crosshair {
		width: 35px;
		height: 35px;
	}

	.dot {
		width: 7px;
		height: 7px;
	}

	.crosshair {
		&:before, &:after {
		  transition-delay: 0.05s
		}
    
    &:nth-child(odd) {
			&:before, &:after {
				width: 16px;
			}
		}

		&:nth-child(even) {
			&:before, &:after {
				height: 16px;
			}
		}
	}
}

} // cursor








// example styles [do not copy]

body {
  height: 100vh;
	background: #20262E;
	color: white;
	margin: 0;
	padding: 20px;
	font-size: 24px;
	font-family: Helvetica;
}

a {
	color: skyblue;
}

JavaScript

const cursor = document.querySelector('.cursor');
        
// cursor object following path of mouse
document.addEventListener('mousemove', e => {
  cursor.setAttribute("style", "top: "+(e.pageY - 5)+"px; left: "+(e.pageX - 5)+"px;")
})

// add animation class to cursor on click
document.addEventListener('click', () => {
  cursor.classList.add("expand");

  setTimeout(() => {
    cursor.classList.remove("expand");
  }, 500)
})

// add class to cursor when hovering <a> tags
$('a').hover(function() {
  $('.cursor').toggleClass('bullseye');
});