How to implement custom events in jQuery?


Custom event means you can create your own events in jQuery. For example, create a custom event to fire an alert box on pressing any key on the keyboard.

Example

You can try to run the following code to learn how to create a custom event,

Live Demo

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   $('textarea').bind("enterKey",function(e){
     alert("You have pressed Enter key!");
   });
   $('textarea').keyup(function(e){
     if(e.keyCode == 13)
     {
        $(this).trigger("enterKey");
     }
   });
});
</script>
</head>
<body>
<textarea rows="2" cols="20">  
</textarea>
</body>
</html>

Updated on: 14-Feb-2020

778 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements