How to detect events on a border of a div element [VUEJS]?

I would like to detect events on a border of an div element in vue.js.

Is there a way? that could look like this:

<div @borderMouseDown="someMethod"></div>

The Solution that worked for my use-case:

borderHandler(event){
        var x = event.offsetX;
        var y = event.offsetY;
        if(
            (x < 0 || x > this.width)
            ||
            (y < 0 || y > this.height)
          )
        {
            alert("Border Pressed");
        }
    },

Answer

What you can do is try to calculate using some math and click event parameters if the mouse is inside the border.

Try clicking the borders in the example below, and you’ll see this in actions by the element changing color, and logging some text below it.

Vue.component('my-component', {
    template: "#my-component",
    data() {
       return { messages: [], color: "red" }
    },
    methods: {
        handleClick(ev) {
           const x = ev.clientX;
           const y = ev.clientY;
           
           const borderSize = this.borderSize(this.$refs.box);
           
           const rect = this.$refs.box.getBoundingClientRect();
           if ( (x >= rect.x && x <= rect.x + borderSize) ||
                (x >= rect.x + rect.width - borderSize 
                  && x <= rect.x + rect.width) || 
                (y >= rect.y && y <= rect.y + borderSize) ||
                (y >= rect.y + rect.height - borderSize &&
                 y <= rect.y + rect.height)) {
              this.handleInsideBorders();
           }
        },
        borderSize(box) {
          return parseInt(getComputedStyle(box).getPropertyValue('border-left-width'));
        },
        handleInsideBorders() {
           this.messages.push("I'm inside borders");
           
           if (this.color === 'red') {
              this.color = 'yellow';
           } else {
              this.color = 'red';
           }
        }
    }
});


new Vue({
  template: "<my-component>></my-component>"
}).$mount("#app");
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

.my-box {
  width: 100px;
  height: 100px;
  margin: 5rem auto;
  background: red;
  border: 10px solid green;
  transition: background 500ms ease;
}

.red {
  background: red;
}

.yellow {
  background: yellow;
}

.d-block {
    display: block;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>


<script type="text/x-template" id="my-component">
  <div>
  <div 
    ref="box" 
    @click="handleClick" 
    :class="['my-box', color]">
  </div>
  <span class="d-block" v-for="message in messages">{{ message }}</span>
  </div>
</script>

<div id="app"></div>

Leave a Reply

Your email address will not be published. Required fields are marked *