Trigger method in jQuery

The method trigger is used to call event handlers manually. For example, by calling the trigger method on the desired element, we can also call the event handler. It has the following use cases:

  • trigger(‘event’): call handler for the given event
  • trigger(Event_object): calling a handler using an Event object that contains data about which handler to call

Let’s look at an example. Let’s say we have a table and there are two buttons on the form that use table handlers:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Trigger method in jQuery</title>
</head>
<body>
    <table>
        <tr><td>Word</td><td>Translation</td></tr>
        <tr><td>Cabbage</td><td>Cabbage</td></tr>
        <tr><td>Carrot</td><td>Carrot</td></tr>
        <tr><td>Potato</td><td>Potato</td></tr>
        <tr><td>Tomato</td><td>Tomato</td></tr>
        </table>
        <br>
        <button>Select</button>
        <button>Deselect selection</button>
        <script type="text/javascript">
        $(function(){
            $('table').on('mouseenter', 'tr', function(e){
                $(this).css('background-color', 'silver');
            }).on('mouseout', 'tr', function(e){
                $(this).css('background-color', 'white');
            });
             
            $('button').first().bind('click', function(){
                $('tr').trigger('mouseenter');
            });
             
            $('button').last().bind('click', function(){
                $('tr').trigger('mouseout');
            });
             
        });
        </script>
</body>
</html>

Trigger method in jQuery
First, we already have table row handlers defined for the mouse enter and events mouse out. We then have handlers defined for the two buttons. Since the first button is intended to select table rows, when it is pressed, the mouse enter event handler defined for table rows is called. And on pressing the second button – the mouse out event handler.