February 09, 2025
Define bind() and unbind() methods in jQuery
In jQuery, we use bind and unbind methods for advanced event handling. Through bind and unbind methods we can bind multiples events in single statement, it saves us writing lot of lines of code. We can unbind events through unbind method which are bind through bind methods only. Below are examples
bind method
bind methods takes two arguments, first is event type string and second is event handler function. bind method can also be called with three arguments, first is event type string, second is called as data object which can be used in event hander function and third is event handler function. Example is mentioned below:
unbind method
Events which are register using bind methods can be unregister with unbind method. It does not deregister events passed to addEventListener().
bind() & unbind() methods example
<html>
<head>
<title>Example</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
</head>
<body>
<button id="btnBeforeText">Before example</button>
<script>
$(document).ready(function () {
var myHandlerFunction = function() {
alert( "bind and unbind method example." );
};
$('#btnText').bind('click', myHandlerFunction);
$('#btnText').bind('mouseenter mouseleave', myHandlerFunction);
$('#btnText').unbind('click', myHandlerFunction);
});
</script>
</body>
</html>