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"> <div>Child1</div> <div>Child2</div> <div>Child3</div> <div>Child4</div> <div>Child5</div> <div>Child6</div> <div>Child7</div> <div>Child8</div> </div>
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.
<script> $("#parent").on('click', function(event){ $(event.target).css('background-color','red'); }); </script>
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.
Be the first to comment.