How can I listen for events on a disabled element? I have an input box that I have disabled but that I want to enable if the user double clicks it. I know this is possible using a label and switching the label off using CSS. I want to know if there is a way to do this without a label – is there some way to disable the input and still handle events for it? or is there a way to make the input unfocusable unless double-clicked?
Advertisement
Answer
You can prevent the default action of the input with a timeout. If a user clicks before the ms has elapsed, you run the desired code:
new Vue({ el: '#app', data: { checked: false, timeoutId: null, // You do not need to have this defined, vue will initialize it for you, but here for clarity }, methods: { dblClick(event) { // Simple click if (!this.timeoutId) { event.preventDefault(); event.stopPropagation(); this.timeoutId = setTimeout(() => { this.timeoutId = null; }, 300); return // Do not run below code if it is a single click } // double click this.timeoutId = null; console.log('dblClick') } } });
#app { display: flex; justify-content: center; align-items: center; flex-direction: column; width: 100%; height: 100vh; } h1 { font-size: 1.5em; margin-bottom: 5px; } i { font-size: .75em; margin: 0; color: #969696; } input { transform: scale(2); margin: 20px 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script> <div id="app"> <h1>Checkbox is {{ checked ? 'checked' : 'not checked' }}</h1> <i>Double-click to change</i> <input v-model="checked" type="checkbox" @click="dblClick"> </div>