jQuery toggleClass example

Toggle class name on click in jQuery

by joshmoto

HTML

<div id="crosshair"></div>

SCSS

BODY {
  width: 100%;
  height: 5000px;
  position: relative;
  cursor: crosshair;
  padding: 0;
  margin: 0;
  background: black;
  
  &:hover {
    
    #crosshair {
      opacity: 1;
      
    }
  }
}

#crosshair {
  opacity: 0;
  transition: all 0.5s ease;

    &::before {
      transition: all 0.5s ease;
      display: block;
      content: '';
      width: 1px;
      height: 100%;
      background: white;
      position: fixed;
      top: 0;
      left: var(--cursor-x);
    }

    &::after {
      transition: all 0.5s ease;
      display: block;
      content: '';
      width: 100%;
      height: 1px;
      background: white;
      position: fixed;
      top: var(--cursor-y);
      left: 0;
    }

}

JavaScript

// our crosshair constant
const crosshair = $('#crosshair');

// document on mouse move
$(document).on('mousemove', function(e) {

  // set css var property --cursor-x position
  crosshair[0].style.setProperty(
  	'--cursor-x', ( e.pageX - $(document).scrollLeft() ) + 'px'
  );
  
  // set css var property --cursor-y position
  crosshair[0].style.setProperty(
  	'--cursor-y', ( e.pageY - $(document).scrollTop() ) + 'px'
  );
  
});