EN
jQuery - remove event
11 points
In this article, we would like to show you how to remove events using jQuery.
xxxxxxxxxx
1
// 1. Dedicated approaches
2
// READ:
3
// 1. jQuery - how to remove event with off method?
4
// 2. jQuery - how to remove event with unbind method?
5
6
// 2. Removing handler with removeAttr method examples
7
8
// 2.1. When event has been added in HTML
9
$('#my-button').removeAttr('onclick'); // removing event attribute
10
11
// 2.2. When event has been added in JavaScript
12
$('#my-button').prop('onclick', null); // removing event property
- jQuery - how to remove event with
off
method? - introduced in jQuery 1.7 - jQuery - how to remove event with
unbind
method? - deprecated since jQuerry 3.0
This approach is useful when an event has been added as an element attribute (e.g. onclick
).
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script>
5
6
function onClick() {
7
console.log('Event name: click');
8
}
9
10
</script>
11
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
12
</head>
13
<body>
14
<button id="my-button" onclick="onClick();">
15
Click button...
16
</button>
17
<br /><br />
18
<button id="my-cleaner">
19
Remove click event...
20
</button>
21
<script>
22
23
$(document).ready(function() {
24
var button = $('#my-button');
25
26
$('#my-cleaner').on('click', function() {
27
button.removeAttr('onclick'); // removing event attribute
28
})
29
});
30
31
</script>
32
</body>
33
</html>
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script>
5
6
function onClick() {
7
console.log('Event name: click');
8
}
9
10
</script>
11
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
12
</head>
13
<body>
14
<button id="my-button" onclick="onClick();">
15
Click button...
16
</button>
17
<br /><br />
18
<button id="my-cleaner">
19
Remove click event...
20
</button>
21
<script>
22
23
$(document).ready(function() {
24
var button = $('#my-button');
25
26
button.prop('onclick', function() {
27
return onClick;
28
});
29
30
$('#my-cleaner').on('click', function() {
31
button.removeAttr('onclick'); // removing event attribute
32
})
33
});
34
35
</script>
36
</body>
37
</html>
This approach is useful when an event has been added as an element property (e.g. onclick
).
xxxxxxxxxx
1
2
<html>
3
<head>
4
<script>
5
6
function onClick() {
7
console.log('Event name: click');
8
}
9
10
</script>
11
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
12
</head>
13
<body>
14
<button id="my-button">
15
Click button...
16
</button>
17
<br /><br />
18
<button id="my-cleaner">
19
Remove click event...
20
</button>
21
<script>
22
23
$(document).ready(function() {
24
var button = $('#my-button');
25
26
button.prop('onclick', function() {
27
return onClick;
28
});
29
30
$('#my-cleaner').on('click', function() {
31
button.prop('onclick', null); // removing event property
32
})
33
});
34
35
</script>
36
</body>
37
</html>