EN
jQuery - remove event
11
points
In this article, we would like to show you how to remove events using jQuery.
Quick solutions
// 1. Dedicated approaches
// READ:
// 1. jQuery - how to remove event with off method?
// 2. jQuery - how to remove event with unbind method?
// 2. Removing handler with removeAttr method examples
// 2.1. When event has been added in HTML
$('#my-button').removeAttr('onclick'); // removing event attribute
// 2.2. When event has been added in JavaScript
$('#my-button').prop('onclick', null); // removing event property
1. Dedicated approaches:
- 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
2. Removing handler with removeAttr
method examples
This approach is useful when an event has been added as an element attribute (e.g. onclick
).
2.1. When the event has been added in HTML
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script>
function onClick() {
console.log('Event name: click');
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
</head>
<body>
<button id="my-button" onclick="onClick();">
Click button...
</button>
<br /><br />
<button id="my-cleaner">
Remove click event...
</button>
<script>
$(document).ready(function() {
var button = $('#my-button');
$('#my-cleaner').on('click', function() {
button.removeAttr('onclick'); // removing event attribute
})
});
</script>
</body>
</html>
2.2. When the event has been added in JavaScript
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script>
function onClick() {
console.log('Event name: click');
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
</head>
<body>
<button id="my-button" onclick="onClick();">
Click button...
</button>
<br /><br />
<button id="my-cleaner">
Remove click event...
</button>
<script>
$(document).ready(function() {
var button = $('#my-button');
button.prop('onclick', function() {
return onClick;
});
$('#my-cleaner').on('click', function() {
button.removeAttr('onclick'); // removing event attribute
})
});
</script>
</body>
</html>
3. Removing handler with prop
method example
This approach is useful when an event has been added as an element property (e.g. onclick
).
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<script>
function onClick() {
console.log('Event name: click');
}
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.0.0/jquery.js"></script>
</head>
<body>
<button id="my-button">
Click button...
</button>
<br /><br />
<button id="my-cleaner">
Remove click event...
</button>
<script>
$(document).ready(function() {
var button = $('#my-button');
button.prop('onclick', function() {
return onClick;
});
$('#my-cleaner').on('click', function() {
button.prop('onclick', null); // removing event property
})
});
</script>
</body>
</html>