mouse over slope

measure the angle of mouse movement for mega menu function

by roblugt

HTML

<script src="http://vuejs.org/js/vue.min.js"></script>
<div id="demo" :class="classname">
  <div @mousemove="mouseOver">Hover over me!
    <p> last mouse event: ({{ lastEvent.clientX }},{{ lastEvent.clientY }}) </p>
    <p> last movement: {{ lastMovement.x }},{{ lastMovement.y }} </p>
    <p> current slope: {{ currentSlope }} </p>
    <p @mouseover="hover"> hover 1 </p>
    <p @mouseover="hover"> hover 2 </p>
  </div>
</div>

CSS

.green {
  background-color: green;
}

.red {
  background-color: red;
}

JavaScript

var demo = new Vue({
  el: '#demo',
  data: {
    active: false,
    lastEvent: {},
    lastMovement: {
      x: 0,
      y: 0
    },
    currentSlope: 1
  },
  computed: {
    classname: function() {
      if (this.currentSlope > 30 && this.currentSlope < 150)
        return 'green'
      else return 'red'
    }
  },
  methods: {
    mouseOver: function(event) {
      // filter out small movements
      //debugger;
      if (this.lastEvent && this.lastEvent.clientX) {
        var mv = this.getMovement(this.lastEvent, event);
        this.lastMovement = mv;
        if (Math.abs(mv.x) > 5 || Math.abs(mv.y) > 5) {
          this.currentSlope = Math.atan2(mv.x, mv.y) * 180 / Math.PI;
          this.lastEvent = event;
        }
      } else {
        this.lastEvent = event;
      }
    },
    hover: function(event) {
      this.active = !this.active;
    },
    getMovement: function(lastEvent, nextEvent) {
      var xm = nextEvent.clientX - lastEvent.clientX;
      var ym = lastEvent.clientY - nextEvent.clientY;
      return {
        x: xm,
        y: ym
      };
    }
  }
});