Add and remove event handler with on and off - Javascript jQuery Method and Property

Javascript examples for jQuery Method and Property:on

Description

Add and remove event handler with on and off

Demo Code

ResultView the demo in separate window

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
    $("p").on("click", function(){
        $(this).css("background-color", "red");
    });/*from ww  w.j  ava2  s .co  m*/
    $("button").click(function(){
        $("p").off("click");
    });
});
</script>
</head>
<body>

<p>Click this paragraph to change its background color.</p>
<p>Click the button below and then click on this paragraph (the click event is removed).</p>

<button>Remove the click event handler</button>

</body>
</html>

Related Tutorials