Tuesday, September 18, 2018

JavaScript - Events - Event Behaviors

In JavaScript there are certain events we need to know. Consider the following body code:

<body>
  <div style="width: 100px
              ; height: 100px
              ; background-color:green"
       id = "greenDiv">
    <div style="width: 40px
                ; height:40px
                ;background-color:yellow"
         id = "yellowDiv">  </div></div>
</body>




This is a nested HTML code - where the yellow div square is inside the green div square. Now, let us add a click listener to the yellow div here.

var yellow = document.querySelector("#yellowDiv");

yellow.addEventListener("click", yellowListener);

function yellowListener(event){
  console.log("clicked Yellow Square!");
}

var green = document.querySelector("#greenDiv");

green.addEventListener("click", greenListener);

function greenListener(event){
  console.log("clicked Green Square!");
}


Now, the question is - where does this event argument come from?
JavaScript passes this event object automatically to the listeners and this object will depend on the type of event. Example:
  • mouse Click Events
  • mouse Enter Events

different types of events to which you can listen and all those types will have their own properties and methods which we can access on the event object which we are passing as the argument here. To use the object is optional. 

Now, to find out more about which properties and methods are available for each event object. We can do the following:
- log it to the console and have a look there. 
- google for JavaScript click event and we can get access to articles with information.

Now what happens when I click on the yellow button. We get two messages. This is because events in JavaScript by default - propagate. This means that:
If I am clicking on the yellow div here. It means that I am also clicking on the green div. Since, the green one holds the yellow square. 

Now, if i don't want the propagation to occur then, I need to modify the yellowListener function to include the event.stopPropagation():

function yellowListener(event){
  event.stopPropagation();
  console.log("clicked Yellow Square!");
}

Hence stopPropagation is a very important method here. We can check if the event has the tendency to bubble up. 

function yellowListener(event){
  console.log(event.bubbles);
  event.stopPropagation();
  console.log("clicked Yellow Square!");
}

We can see that true is output to the console.


No comments:

Post a Comment