Posts

What is Event Delegtion in Javascript? Famous Javascript Interview question

Image
  Do you know what is event delegation?  If this question is asked in an interview you can give these two examples and interviewer will be impressed. Event Delegation is based on Event bubbling. Let's understand with example. Suppose we are creating Ecommerce website and there are lot of categories inside it like shoes, clothings, and lot more . When we click on shoes it takes us to different page. if we click on clothings and takes it to a different page. So in each category we have to attach events. What if there are lot of categories this is not good for optimisation then. So instead of attaching to each category we will try to just attach it to parent element. So because of event bubbling the events are propagating up the hierarchy to the parent element. Lets understand with code: Here, the element with id categories is the parent element and element with id laptop, phone and chargers is child element. Now for event delegation we will attach the event at parent element and let&