Reading list Switch to dark mode

    JavaScript Event Delegation

    Updated 22 August 2017

    Many times we use some methodologies in our code but we don’t know about the actual technical term of those methodologies. Today we will learn about one of the interesting methodologies in JavaScript that is Event Delegation. JavaScript event delegation is a simple technique by which you can add a single event handler to the parent instead of adding same event handler to his multiple child elements.

    The base concept is very simple but many people don’t understand how event delegation works. Let me explain how event delegation works and provide basic JavaScript example of event delegation.

    <div id="parent">

    In the above example there is an parent element with id is parent and some child div elements of this parent div element. In general process if we need to change background color to red of each div element then we need to add event handler to each div element but by the event delegation methodology if we add a single event handler to the parent div element then this event will work for all the child element of this parent div element. If we discriminate each element means when you click on one element then only that div element background color will be changed to red. Then we need to use the “target” key of the event object.

      $("#parent").on('click', function(event){

    Benefits of JavaScript Event Delegation :-

    • By this we can minimize lot’s of same event handler to each element.
    • If page is generated through dynamically or AJAX then no need to add and remove event handlers as elements are loaded or unloaded.

    Start your headless eCommerce
    Find out More
    . . .

    Leave a Comment

    Your email address will not be published. Required fields are marked*

    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home