Direction Aware Box Shadow In JavaScript

Category: Javascript | November 19, 2019
Author:Mert Cukuren
Views Total:1,073 views
Official Page:Go to website
Last Update:November 19, 2019
License:MIT

Preview:

Direction Aware Box Shadow In JavaScript

Description:

A JavaScript class that applies an interactive, direction-aware box shadow effect to DOM elements.

It makes it possible to dynamically adjust the position of the box-shadow effect depending on the direction your cursor enters the element.

How to use it:

1. The core DirectionAwareShadow class.

class DirectionAwareShadow {
  constructor({
    target = null,
    blur = 0,
    spread = 0,
    inset = false,
    reverse = false,
    color = 'currentColor',
    offset = 1
  } = {}) {
    this.target = target ? document.querySelectorAll(target) : target;
    this.blur = blur;
    this.inset = inset;
    this.spread = spread;
    this.reverse = reverse;
    this.color = color;
    this.offset = offset;
  }
  move() {
    this.target.forEach(t =>
      t.addEventListener('mousemove', e => this.calc(e))
    );
  }
  px(val) {
    return `${val}px`;
  }
  calc(e) {
    const { currentTarget, offsetX, offsetY } = e;
    const { offsetHeight, offsetWidth } = currentTarget;
    const { color, reverse, offset } = this;
    
    const blur = this.px(this.blur);
    const spread = this.px(this.spread);
    const inset = this.inset ? 'inset' : '';
  
    const x = ((offsetWidth / 2 - offsetX) * offset) / 2;
    const y = ((offsetHeight / 2 - offsetY) * offset) / 2;
 
    const h = this.px(!reverse ? x : x * -1);
    const v = this.px(!reverse ? y : y * -1);
    currentTarget.style.boxShadow = `${h} ${v} ${blur} ${spread} ${color} ${inset}`;
  }
  init() {
    if (!this.target) {
      console.error('[direction-aware shadow] • you should add a target')
      return;
    }
    this.move();
  }
}

2. Create a new DirectionAwareShadow and config the shadow effect with the following parameters:

const instance = new DirectionAwareShadow({
      target: '.yourElement',
      blur: 30,
      spread: 0,
      offset: .8,
      color: 'rgba(79, 1, 119, 0.36)',
      inset: false,
      reverse: false
});

3. Initialize the direction aware shadow effect and done.

instance.init();

You Might Be Interested In:


One thought on “Direction Aware Box Shadow In JavaScript

  1. Lawrence

    this is amazing!!! is there a way to only make the shadow show when the target is hovered and go away when it is no longer hovered?

    Reply

Leave a Reply