Registering and deleting event handlers In jQuery

Events allow us to track the state of an element and process user input. Using standard JavaScript code, we could handle the event right in the element’s markup using the appropriate attributes. For example, let’s handle a button click:

<button onclick="alert('Hello World');">Click</button>

To handle the button press, some actions are set, for example, as in this case, displaying a message.

The jQuery library provides us with a spectacular way to register event handlers on elements using the bind.

The bind method has the following syntax: bind(‘event_type’, event_handler_function). For example, let’s handle a button click with jQuery:

<button class="redStyle">Press</button>
<script type="text/javascript">
$(function(){
    $('button').bind('click', function(){
        alert('Hello world!');
    });
});
</script>

Using an expression in the handler, $(this)we can get the element on which the event was fired. Using element properties, you can specify more complex event handling logic. For example, let’s say we have several buttons on the page, and the actions will differ depending on the button pressed:

 
<button class="langs">Programming languages</button>
<script type="text/javascript">
$(function(){
    $('button').bind('click', function(){
        if($(this).hasClass("langs")){
            $('body').append('<ul><li>Java</li><li>JavaScript</li></ul>');
        }
        alert('Click event handler');
    });
});
</script>

Thus, if we have several buttons on the page, then only in the case of one, by clicking on it, a list will be added to the page. In other cases, a message will simply be displayed on the screen.

When using the bind method, it is important to consider that it adds handlers for already existing elements. Handlers will not be applied to dynamically added elements.

unbind method

If, for some reason, we no longer need to handle an event, then we can unregister the associated handler with the unbind:

$('button').bind('click', function(e){
    alert('Hello world!');
});
$('button').unbind();

Single event processing. Method one

The method one allows you to set an event handler for the element, which will fire only once. After processing, the handler will be deleted:

<button>Press1</button>
<button>Press2</button>
<button>Press3</button>
<script type="text/javascript">
$(function(){
    $('button').one('click', function(e){
        $(this).css('color', 'red');
        alert('Button handler: '+$(this).text());
    });
});
</script>

As a result, the handler of each button will work once.