Handle common event handler for multiple element

Handle common event handler for multiple element
Handle common event handler for multiple element


Here is simple code sample given for handle common event handler for multiple DOM elements.

For example you have 3-4 anchor tags in page. Now you want to change anchor tag colour, when anchor tag clicked. So it’s better to write common event for all anchor tag compare to separate event for each anchor.

Now how you do it?

You can achieve it using class attribute and jQuery.

Here are steps to handle common event handler for multiple element.

  1. Set same class to all element
  2. Write common event for class
  3. Get particular element and make process on it

Set same class to all element

<a href="javascript:;" id="linkOne" class="commonClass">Link 1</a>
<a href="javascript:;" id="linkTwo" class="commonClass">Link 2</a>
<a href="javascript:;" id="linkThree" class="commonClass">Link 3</a>

Write common event for class

$(function(){
    $('.commonClass').click(function(){

    });
});

Get particular element and make process on it

$(function(){
    $('.commonClass').click(function(){
        alert(this.id);
        $(this).css('color', 'green');
    });
});

Extra tip

For dynamically created element use on/live based on your jQuery version.

$(function(){
    $('.commonClass').on('click', function(){
        alert(this.id);
        $(this).css('color', 'green');
    });
});

That’s it, Hope you like this simple code snippet.