Create Custom Events using jQuery trigger() Method

← PrevNext →

One of most basic requirement of client side programming is the way events are handled and executed. However, with the advent of modern browsers, custom events written in JavaScript started losing steam and developers started looking for simpler and platform independent ways to deal with events.

jQuery .trigger() method has changed the way custom events will be created, handled and later executed. Not just click but all events that are bound with an element, can be triggered using this method.

See this demo

We can put it in this way. The user is asked to fill a few textboxes with data and once filled a button will be clicked to submit the contents of the webpage.

Instead of clicking the button, the user hits the enter key immediately after typing some value in the textbox, and that too triggers an event and submits the contents.

There were two events at work, not simultaneously but in a row. Since the cursor was still inside the textbox, the first event reported is the keypress event of the textbox which actually triggers the “click” event of the button, meant for submitting the data or the content.

<html>
<body>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

    Enter your name <input type="text" id="tb" />
    <input type="button" id="btContinue" value="Submit" />
</body>

<script>
    $(document).ready(function() {
        $('input').keypress(function(event) {
            if (event.keyCode == 13) $('#btContinue').trigger('click');
        });

        $('#btContinue').click(function() {
            alert('Hi, ' + $('input').val());
        });
    });
</script>
</html>
Try it
In the above example, we are first checking if the key pressed inside the textbox is the enter key, for which the keycode is 13. Now the keycode is captured using the keypress event of the input box which is also a textbox.
With Multiple Elements

Note that we have 2 input boxes, a textbox and a button. We can do this more specifically by identifying the elements with its ID. This is important since a web page can have multiple textboxes each with events and out of many controls only one should trigger the click event of the button.

<body>
    Company <input type="text" id="tbCompany" /><br />
    Enter your name <input type="text" id="tbName" />
    
    <input type="button" id="btContinue" value="Submit" />
</body>
<script>
    $(document).ready(function() {
        $('#tbName').keypress(function(event) {
            if (event.keyCode == 13) $('#btContinue').trigger('click');
        });

        $('#btContinue').click(function() {
            alert('Hi, ' + $('#tbName').val());
        });
    });
</script>

See this Demo

Press the Enter Key after entering your name. This will trigger the Submit button.

Your Company

Enter your name

Well, that's it. Thanks for reading.

← PreviousNext →