JQuery on() & off() with selectors
by Bryson Murray
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button id="theone">Does nothing...</button>
<button id="bind">Add Click</button>
<button id="unbind">Remove Click</button>
<div style="display:none;">Click!</div>
CSS
button {
margin: 5px;
}
button#theone {
color: red;
background: yellow;
}
JavaScript
function flash() {
$( "div" ).show().fadeOut( "slow" );
}
$( "#bind" ).click(function() {
$("#theone").parent()
/* .on( "click", flash ) */
.on( "click", "#theone", flash )
/* .find( "#theone" ) */
$( "#theone" )
.text( "Can Click!" );
});
$("#unbind").click(function() {
$( "body" )
.off( "click", "#theone", flash )
.find( "#theone" )
.text( "Does nothing..." );
});