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:
JavaScript
x
26
26
1
new Vue({
2
el: '#app',
3
data: {
4
checked: false,
5
timeoutId: null, // You do not need to have this defined, vue will initialize it for you, but here for clarity
6
},
7
methods: {
8
dblClick(event) {
9
// Simple click
10
if (!this.timeoutId) {
11
event.preventDefault();
12
event.stopPropagation();
13
14
this.timeoutId = setTimeout(() => {
15
this.timeoutId = null;
16
}, 300);
17
18
return // Do not run below code if it is a single click
19
}
20
21
// double click
22
this.timeoutId = null;
23
console.log('dblClick')
24
}
25
}
26
});
JavaScript
1
24
24
1
#app {
2
display: flex;
3
justify-content: center;
4
align-items: center;
5
flex-direction: column;
6
width: 100%;
7
height: 100vh;
8
}
9
10
h1 {
11
font-size: 1.5em;
12
margin-bottom: 5px;
13
}
14
15
i {
16
font-size: .75em;
17
margin: 0;
18
color: #969696;
19
}
20
21
input {
22
transform: scale(2);
23
margin: 20px 0;
24
}
JavaScript
1
6
1
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
2
<div id="app">
3
<h1>Checkbox is {{ checked ? 'checked' : 'not checked' }}</h1>
4
<i>Double-click to change</i>
5
<input v-model="checked" type="checkbox" @click="dblClick">
6
</div>