Getting Started with Vue.js

Vue Events: Building a Crazy Button

Let's use Vue to do a technique that is completely not practical! We're going to make it near impossible for our users to click on a button.

We'll use Vue to listen for the mouseenter DOM event. We'll then generate a random number and apply those numbers to the button styles.

Vue makes all the above very easy since all we have to do is update data and Vue will handle changing the template and HTML to reflect those changes.


We'll have a quick button:

<div id="app">
        class="button is-info is-crazy" 
            Catch me if you can!

Here we are binding an object to the element's styles. We are also listening for the mouseenter event and then calling a moveButton method whenever that happens.

The Vue JavaScript

We'll be using Math.random() from Javascript's Math object to generate a number between 0 and 1. We'll also grab the window's height using window.innerHeight.

const app = new Vue({
    el: '#app',
    data: {
        buttonOffsets: {
            top: null,
            left: null
    methods: {
        moveButton: function(e) {
            this.buttonOffsets = {
              top: `${Math.random() * window.innerHeight}px`,
              left: `${Math.random() * window.innerWidth}px`

Like this article? Follow @chrisoncode on Twitter